Redux-toolkit: Why do we need to check the loading state for createAsyncThunk reducers?

Created on 8 Mar 2020  路  1Comment  路  Source: reduxjs/redux-toolkit

In the documentation for createAsyncThunk, within the extra reducers the loading state is being checked.

extraReducers: {
    [fetchUserById.pending]: (state, action) => {
      if (state.loading === 'idle') {
        state.loading = 'pending'
      }
    },
    [fetchUserById.fulfilled]: (state, action) => {
      if (state.loading === 'pending') {
        state.loading = 'idle'
        state.push(action.payload)
      }
    },
    [fetchUserById.rejected]: (state, action) => {
      if (state.loading === 'pending') {
        state.loading = 'idle'
        state.error = action.error
      }
    }
  }

Will the loading state not be predictable by default? Is there a chance that .fulfilled is called while the loading state has not been set to pending in the .pending function?

Most helpful comment

The "loading state" is whatever values you want to use. Traditionally, that's been something like {isLoading: boolean, error: string}. We're starting to try to encourage using some kind of an enum instead of booleans.

As for the timing thing, imagine a case where the user double-clicked on a button and triggered a fetch request twice. You'd probably only want the result to get handled one time.

>All comments

The "loading state" is whatever values you want to use. Traditionally, that's been something like {isLoading: boolean, error: string}. We're starting to try to encourage using some kind of an enum instead of booleans.

As for the timing thing, imagine a case where the user double-clicked on a button and triggered a fetch request twice. You'd probably only want the result to get handled one time.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nonissue picture nonissue  路  3Comments

emil14 picture emil14  路  3Comments

ouweiya picture ouweiya  路  3Comments

Darrekt picture Darrekt  路  3Comments

cole-robertson picture cole-robertson  路  3Comments