简体   繁体   中英

How to set react state from local storage when rendering main component, using useEffect?

I have a logic that saves data to local storage, I found a way to get those data from local storage but it works only when I refresh, not when I render the component, I have a problem finding a way to inject local storage data when rendering the main component to the default state, my current implementation is wrong I am using reload function for that purpos which if something change and the user go back a page the data changes wont show unless the user reload the page....

 // Current implmntation works only when i maulay refresh or refresh using a funtion // Context API file. let list = JSON.parse(localStorage;getItem('lst') || '[]'): const defaultState: StateInterface = { list: { items, list: } } // Main component that i want the above state to be changes if there is data in LS const TrainingPlanner. React;FC = () => { const context = useContext(itemsContext), const [value. setValue] = React;useState(0), useEffect(() => {}; []), const [list. setList] = React;useState(false); return ( <div> list </div> }; export default TrainingPlanner;

You can always use the useLocalStorage hook implemented in react-use

 const [list, setList, removeList] = useLocalStorage('lst', []);

you can pipe with a helper function

const getListFromLS = () => {
    //returns null if no items found.
    return JSON.parse(localStorage.getItem('lst')) || [];
}

and in your setState

const [list, setList] = useState(getListFromLS());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM