Amin
Amin

Reputation: 895

Redux state doesn't update immediately

I have super simple question Why my redux state doesn't update immediately?

const { reducer, actions } = createSlice({
  name: "professionals",
  initialState: {
    loading: false,
    lastFetchList: undefined,
    list: undefined,
    professional: undefined,
    filters: {
      virtual: false
    }
  },
  reducers: {
    professionalsListRequested: (professionals, action) => {
      if (action.payload.withLoading) professionals.loading = true;
    },
    professionalsListRequestFailed: (professionals, action) => {
      professionals.loading = false;
    },
    professionalsListReceived: (professionals, action) => {
      professionals.lastFetchList = Date.now();
      professionals.list = action.payload.data.dataArr;
      professionals.loading = false;
    },
    virtualUpdated: (categories, action) => {
      categories.filters.virtual = action.payload;
    }
  },
});
export const { virtualUpdated } = actions;
export default reducer;

it is my slice. and here is code of the component :

  const dispatch = useDispatch();
  const filters = useSelector((state) => state.professionals.filters);
  const handlePressOnVirtual = async () => {
    console.log("Before" , filters.virtual)
    await dispatch(virtualUpdated(!filters.virtual));
    console.log("after" , filters.virtual)
  };

when handlePressOnVirtual function is called the both console.log(s) print previous value of the state.

Upvotes: 0

Views: 1441

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

When you are still in handlePressOnVirtual function, you are still in a closure, so all the references will still be your existing filters

So you would need to wait for another re-render for useSelector to invoke again then the new values will come.

  • One way to see the latest changes is to put your log inside a useEffect:
useEffect(() => {
  console.log("after" , filters.virtual)
},[filters.virtual]);

Upvotes: 2

Related Questions