Search code examples
reduxredux-sagaredux-observableredux-toolkit

Catch all Pending or Rejected actions within a redux-toolkit slice


Aight.. so im pretty new with redux toolkit and I want to catch ALL pending actions in one slice to basically show a loading modal. I know we can do this with redux-saga and probably redux-observable

Soooooo instead of

 builder.addCase(fetchUsers.pending, (state) => {
      state.loading = LoadingState.PENDING;
 });

To Something like this

 builder.addCase(allActions.pending, (state) => {
      state.loading = LoadingState.PENDING;
 });

I know allActions does not work there but is there anything that will.


Solution

  • You can use the matching utilities included in RTK:

    import { createSlice, isPending} from "@reduxjs/toolkit";
    
    const dataSlice = createSlice({
      name: "data",
      reducers: { /* */ },
      extraReducers: builder => {
        builder.addMatcher(isPending, (state, action) => {
          // logic here
        })
    
      }
    })
    

    You can also combine the matching utilities in various ways to only handle the pending state for specific thunks, etc.