Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 599
Zohaib Ahmad Avatar asked Oct 17 '25 03:10

Zohaib Ahmad


1 Answers

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.

like image 128
markerikson Avatar answered Oct 19 '25 01:10

markerikson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!