Redux-toolkit: A Way to Track Loading status of requests created through createAsyncThunk

Created on 9 Mar 2021  路  1Comment  路  Source: reduxjs/redux-toolkit

Its hard to keep track of loading/processing state for async thunks.

There are some methods available which adds extra boilerplate code
For example : adding a variable to redux state .

Feature:
Add a reducer that holds state for all the loading states for async thunk

And then use a selector to get the state

Most helpful comment

There is a new API we are going to add specifically for caching of API responses that is currently available in beta under https://rtk-query-docs.netlify.app/ - I higly recommend that you take a look there.

But apart from such specific and opinioned use cases, providing more general mechanisms is just not feasible, as there are too many different approaches. It is quite easy to just write a small abstraction for it yourself for exactly your use case though.

One example could be

function trackLoadingState(builder, asyncThunk) {
  builder.addCase(asyncThunk.pending, state => void state.status = 'pending');
  builder.addCase(asyncThunk.fulfilled, state => void state.status = 'fulfilled');
  builder.addCase(asyncThunk.rejected, state => void state.status = 'rejected' );  
}

// in your slice
const slice = createSlice({
  // ...
  extraReducers(builder) {
    trackLoadingState(builder, myThunk)
  }
})

but others maybe want to track loading state per slice per asyncThunk type, per request, or in a separate slice for all requests. There is just not one way.

>All comments

There is a new API we are going to add specifically for caching of API responses that is currently available in beta under https://rtk-query-docs.netlify.app/ - I higly recommend that you take a look there.

But apart from such specific and opinioned use cases, providing more general mechanisms is just not feasible, as there are too many different approaches. It is quite easy to just write a small abstraction for it yourself for exactly your use case though.

One example could be

function trackLoadingState(builder, asyncThunk) {
  builder.addCase(asyncThunk.pending, state => void state.status = 'pending');
  builder.addCase(asyncThunk.fulfilled, state => void state.status = 'fulfilled');
  builder.addCase(asyncThunk.rejected, state => void state.status = 'rejected' );  
}

// in your slice
const slice = createSlice({
  // ...
  extraReducers(builder) {
    trackLoadingState(builder, myThunk)
  }
})

but others maybe want to track loading state per slice per asyncThunk type, per request, or in a separate slice for all requests. There is just not one way.

Was this page helpful?
0 / 5 - 0 ratings