Home > database >  Redux toolkit state is not updating after API response
Redux toolkit state is not updating after API response

Time:09-24

new to redux toolkit.

Redux reducer not updating the state after API response, if update the state before API call its working fine, described my code in below

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  value: 0,
};

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    allUsers: (state) => {
      state.value = 2; //state is updating here
      fetch("http://bss-api.test/api/admin/users")
        .then((response) => response.json())
        .then((result) => {
          state.value = 5; //state is not updating here
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },
});

export const { allUsers } = userSlice.actions;
export default userSlice.reducer;

CodePudding user response:

You must never run any async logic in a reducer:

Any async logic belongs outside the reducer, such as in a thunk:

Additionally, all Redux updates are caused by dispatching an action.

We'd recommend using RTK's createAsyncThunk utility to help define and dispatch actions automatically based on the promise from the request:

CodePudding user response:

resolved this problem by understanding createAsyncThunk utility of RTK's

described in code below

import { createSlice, createAsyncThunk} from "@reduxjs/toolkit";

export const getUsers = createAsyncThunk(
    'getUsers',
    async ({ limit }, { dispatch, getState }) => {
      return fetch(
        `http://bss-api.test/api/admin/users`
      ).then((res) => res.json())
    }
  )

export const userSlice = createSlice({
name:'user',
initialState:{
    list:[],
    status:null
},
extraReducers: {
    [getUsers.pending]: (state, action) => {
      state.status = 'loading'
    },
    [getUsers.fulfilled]: (state, { payload }) => {
      state.list = payload
      state.status = 'success'
    },
    [getUsers.rejected]: (state, action) => {
      state.status = 'failed'
    },
  },
});


export default userSlice.reducer
  • Related