I have this hook
const [folders, setFolders] = useState([]);
How can I local store this data so when you refresh the page data in useState saves
you might store the data in the localStorage, but when you use the setFolders()
function, you must update it in localStorage.
Your code should look like this:
const [folders, setFolders] = useState(JSON.parse(localStorage.getItem('folders')) || [])
const setFoldersStorage = (new) => { setFolders(new); localStorage.setItem('folders', JSON.stringify(new)); }
when you want to update folders , you use the setFoldersStorage()
// Retrieve the initial data from the localStorage
const [folders, setFolders] = useState(
() => JSON.parse(localStorage.getItem("folders") || "[]"));
// store the value into the localStorage whenever folders is updated
useEffect(() => {
localStorage.setItem("folders", JSON.stringify(folders));
}, [folders]);
You can also create a custom hook so you can reuse it
function useStateLs(initValue, lsKey) {
const [value, setValue] = useState(
() => JSON.parse(localStorage.getItem(lsKey) || JSON.stringify(initValue))
);
useEffect(() => {
localStorage.setItem(lsKey, JSON.stringify(value));
}, [value]);
return [value, setValue];
}
const [folders, setFolders] = useStateLs([], "folders");
So mainly, what you need is to set an item to the local storage every time the folders
state changes and at the same time update setFolders
every time the component re-renders.
function MyComponent(){
const [folders, setFolders] = useState([])
// update setFolders with the local storage data
useEffect(() => {
setFolders(JSON.parse(window.localStorage.getItem('folders')))
}, [])
// save folders state in local storage when it changes
useEffect(() => {
window.localStorage.setItem('folders', folders)
}, [folders])
return <>{folders}</>
}
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.