'Convert a typesafe-actions (createAsycAction) code segment to reduxjs/toolkit (createAsyncThunk)

I'm converting my react store from typesafe-actions to @reduxjs/toolkit. I need some direction on how to convert the following code snippet:

export const fetchAllCollectiblesAsync = createAsyncAction(
    'collectibles/ALL_COLLECTIBLES_fetch_request',
    'collectibles/ALL_COLLECTIBLES_fetch_success',
    'collectibles/ALL_COLLECTIBLES_fetch_failure',
)<
    void,
    {
        collectibles: Collectible[];
    },
    Error
>();

I'm just looking for the createAsyncThunk version of this. Cheers, Dave



Solution 1:[1]

Check documentation for createAsyncThunk and for extraReducers parameter of createSlice function, I think this is exactly what you need:

/* action to fetch */
const fetchAllCollectiblesAsync = createAsyncThunk(
  'collectibles/ALL_COLLECTIBLES',
  async (collectibles: Collectible[]) => {
    /* ... */
  }
)

/* the part of slice */
const slice = createSlice({
  extraReducers: (builder) => {
    builder.addCase(fetchAllCollectiblesAsync.pending, () => {
      /* handler for request */
    })
    .addCase(fetchAllCollectiblesAsync.fulfilled, () => {
      /* handler for success */
    })
    .addCase(fetchAllCollectiblesAsync.rejected, () => {
      /* handler for error */
    })
  }
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mike Kokadii