reactjsreact-reduxredux-thunkredux-toolkit

Redux toolkit update state in thunk


I have an initial state like this.

const initialState = {
    loading: false,
    products: []
}

For the get products, I use thunk and I fetch datas from an API. loading field describes status of API call. If loading is true, i show progress in my component.

export const getProducts = createAsyncThunk('product/getProducts ',
    async (payload, { rejectWithValue }) => {
        try {
            //fetch from somewhere
        }
        catch (e) {
            return rejectWithValue(e.message)
        }
    }
)

const productSlice = createSlice({
    name: "product",
    initialState,
    reducers: {
        setLoading: (state, action) => {
            state.loading = action.payload;
        }
    },
})

In a component first dispatch for loading and then getProducts.

// In some component
  dispatch(setLoading(true))
  dispatch(getProducts())

My question is, can I only call for getProducts and update loading state inside that function?

//In some component
 dispatch(getProducts())

Solution

  • Yes you can. This is very simple

    Update your createSlice section like this

    const productSlice = createSlice({
        name: "product",
        initialState,
        reducers: {},
        extraReducers: (builder) => {
          builder.addCase(getProducts.pending, (state) => {
            state.loading = true;
          });
    
          builder.addCase(getProducts.fulfilled, (state) => {
            state.loading = false;
          });
        },
    })