Hey everybody hope you are fine
I am trying to set the dark mode for my react app and I am then updating the state containing dark mode but the problem is that even after using localStorage
I am unable to make it on reload
const { modes } = useSelector((state) => state.DarkMode);
console.log("this is modes " + modes);
const onChangeButton = () =>{
let modeSet = localStorage.getItem("moding")
if (modeSet === null) {
modeSet = true
localStorage.setItem("moding",modeSet)
}
else if (modeSet !== null){
if (modeSet === true) {
modeSet = false;
localStorage.setItem("moding",modeSet)
console.log("iam in true");
} else {
modeSet = true;
localStorage.setItem("moding",modeSet)
console.log("iam in false");
}
}
dispatch(setDarkMode(modeSet));
}
useEffect(() => {
onChangeButton();
}, []);
and I am also changing it with a button
<button className="modeBtn modeBtn1" onClick={() =>onChangeButton()} style={{color: `${modes ? "white" : "black"}`, backgroundColor: `${modes ? "black" : "white"}`,}}>{`${modes ? "Light ☀️" : "Dark "}`}</button>
and in the redux actions which is the main function of changing the state is
export const setDarkMode = (moder) => async (dispatch) => {
console.log("this is inside moder " + moder);
let data = moder;
dispatch({
type: SET_DARK_MODE,
payload: data,
});
};
the problem is that when I change the theme with the button it takes changing the mode to the dark mode and works fine but when I reload it moves back again to the white mode. how can I make it stay and change on button.