Home > Software engineering >  Reducers is not updating the state in redux toolkit
Reducers is not updating the state in redux toolkit

Time:11-20

Want to open and close the navigation drawer by clicking on the navbar icon this is inside header component and storing the value in slice using redux toolkit that is in util.js

<img
          src={NavIcon}
          alt=""
          className="icon nav-icon colapse-icon"
          onClick={() => {
            setDrawer(!drawer);
            !drawer
              ? dispatch(drawerOpneClose(true))
              : dispatch(drawerOpneClose(false));
          }}
        />

Util.js slice code

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

const UtilSlice = createSlice({
  name: "util",
  initialState: { openDrawer: true },
  reducers: {
    drawerOpneClose: (state, action) => {
      return {
        ...state,
        openDrawer: action.payload,
      };
    },
  },
});

export const UtilReducer = UtilSlice.reducer;
export const { closeNav, openNav, drawerOpneClose } = UtilSlice.actions;

Leistinig for change in data in SideBar.js

function SideBar() {
const [drawer] = useState(useSelector((state) => state.util) || false);

  console.log(drawer);

  return (
    <div className={`${true ? "open-nav" : "close-nav"}`}>
   )

}

State value is not getting updated as initially it is true it stays true if i pass false it is not getting updated

CodePudding user response:

useState won't update the state value when the reducer updates.

Just use the selector value

const {openDrawer} = useSelector((state) => state.util);


 return (
    <div className={`${openDrawer ? "open-nav" : "close-nav"}`}>
   )
  • Related