Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

createasyncthunk with typescript

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'

const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, { getState, requestId }) => {
    const { currentRequestId, loading } = getState().users
    if (loading !== 'pending' || requestId !== currentRequestId) {
      return
    }
    const response = await userAPI.fetchById(userId)
    return response.data
  }
)

const usersSlice = createSlice({
  name: 'users',
  initialState: {
    entities: [],
    loading: 'idle',
    currentRequestId: undefined,
    error: null,
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchUserById.pending, (state, action) => {
        if (state.loading === 'idle') {
          state.loading = 'pending'
          state.currentRequestId = action.meta.requestId
        }
      })
      .addCase(fetchUserById.fulfilled, (state, action) => {
        const { requestId } = action.meta
        if (
          state.loading === 'pending' &&
          state.currentRequestId === requestId
        ) {
          state.loading = 'idle'
          state.entities.push(action.payload)
          state.currentRequestId = undefined
        }
      })
      .addCase(fetchUserById.rejected, (state, action) => {
        const { requestId } = action.meta
        if (
          state.loading === 'pending' &&
          state.currentRequestId === requestId
        ) {
          state.loading = 'idle'
          state.error = action.error
          state.currentRequestId = undefined
        }
      })
  },
})

const UsersComponent = () => {
  const { entities, loading, error } = useSelector((state) => state.users)
  const dispatch = useDispatch()

  const fetchOneUser = async (userId) => {
    try {
      const user = await dispatch(fetchUserById(userId)).unwrap()
      showToast('success', `Fetched ${user.name}`)
    } catch (err) {
      showToast('error', `Fetch failed: ${err.message}`)
    }
  }

  // render UI here
}
Comment

PREVIOUS NEXT
Code Example
Typescript :: create CSS class in directive angular 
Typescript :: salesforce lwc data binding for multiple inputs values 
Typescript :: input deno 
Typescript :: nest js null exclude 
Typescript :: test coverage when tests are in a different package 
Typescript :: The following TestContainer was not found 
Typescript :: react tailwind css components npm 
Typescript :: preventing +,-,e from input ts 
Typescript :: eliminar un elemento de un array typescript 
Typescript :: laravel How to print route lists in Blade 
Typescript :: persists meaning 
Typescript :: change field name relation typeorm 
Typescript :: python ffmpeg convert ts to mp4 
Typescript :: ts date get minutes 
Typescript :: compare two lists and find at least one equal python 
Typescript :: void function typescript 
Typescript :: typescript syntax 
Typescript :: react native styled-components responsive font 
Typescript :: namespaces typescript 
Typescript :: onblur vs valuechange 
Typescript :: how to take inputs in one line in c 
Typescript :: typescript 
Typescript :: typescript wrapping for array 
Typescript :: addObjects giving a fatal error when pushing data to algolia 
Typescript :: dividing a number into digits typescript 
Typescript :: Building a maven EAR project and specifying the configuration of which projects to include, what is the element in the plugin configuration that contains Enterprise Java Bean Projects: 
Typescript :: .env.local is not working inside useEffect 
Typescript :: does i5 7th generation processor supports windows 11 
Typescript :: mongodb node findone how to handle no results using promises 
Typescript :: CREATE FUNCTION which accepts LIST as argument 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =