Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reducers is not updating the state in redux toolkit

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"}`}>
   )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading