Home > front end >  How to local store a useState data in ReactJs
How to local store a useState data in ReactJs

Time:04-12

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

CodePudding user response:

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()

CodePudding user response:

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}</>
  }

CodePudding user response:

// 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)) || initValue
  );
  
  useEffect(() => {
    localStorage.setItem(lsKey, JSON.stringify(value));
  }, [value]);

  return [value, setValue];
}

const [folders, setFolders] = useStateLs([], "folders");
  • Related