Help :) / React Persistent Toggle State

Hello, i tried to create a little React App. Now I added a Toggle, it works perfect, except the State is of course not persistent. So I tried to at the state in the localStorage. It worked, but the Toggle Switch not. Always starts with off on reload. Can anyone help me figure out what is going wrong here? Or is it complete bullshit? :( It's not the complete Code. But I hope it is enough https://code.sololearn.com/WoHDK99Z0R12 Thank you :)

22nd Jan 2022, 12:36 PM
Tobias Brummer
Tobias Brummer - avatar
2 Answers
React is just javascript and javascript runs locally which means nothing is saved untill you tell it to by saving to a database via the server or by localstorage. However localstorage is not recommended as it can be vulnerable to XSS. The best way is to save the toggle state in the React state then use a hook like useEffect, useMemo or when using class components componentDidUpdate to send an ajax request to the server and send the state with the toggle state to the server. Then in your componentDidMount or useEffect hook do another ajax request to get the toggle state from the server and your component will stay toggled even if you reload the page. I saw in your code you use defaultChecked. That prop is for the dom element itself and should not be used like that. Use value or checked instead. React calls that "controled components".
10th Feb 2022, 5:09 PM
Leo - avatar
Due to the asynchronous function of localStorage access, enabled is not updated with the data. You should directly assign the props value to the component <Switch checked={props.defaultChecked} defaultChecked={props.defaultChecked} onChange={(e) => onChange(e)} > Or use useEffect with effect of props to update enabled state in Toggle component. React.useEffect(()=>{ setEnabled(props.defaultChecked); }, [props.defaultChecked)]);
19th Feb 2022, 9:48 AM
Calviղ - avatar