1

I have a react application with a good amount of states. I've been looking around trying to find the best way to save the states to local storage. Honestly, none of the answers were helping so I decided to ask my own.

What's the best way to go about saving these states to local storage?

function Main() {
  const [thumb, setThumb] = useState();
  const [timestamp, setTimestamp] = useState("1:20");
  const [channelPic, setChannelPic] = useState();
  const [title, setTitle] = useState("Title");
  const [channelName, setChannelName] = useState("Channel");
  const [views, setViews] = useState("1,000");
  const [timeAgo, setTimeAgo] = useState("23");
  const [increment, setIncrement] = useState("minute");
  const [verified, setVerified] = useState(false);

  return (
    <div className="d-flex">
      <Preview
        thumb={thumb}
        timestamp={timestamp}
        channelPic={channelPic}
        title={title}
        channelName={channelName}
        views={views}
        timeAgo={timeAgo}
        increment={increment}
        verified={verified}
      />
      <Info
        setThumb={setThumb}
        setTimestamp={setTimestamp}
        setChannelPic={setChannelPic}
        setTitle={setTitle}
        setChannelName={setChannelName}
        setViews={setViews}
        setTimeAgo={setTimeAgo}
        setIncrement={setIncrement}
        setVerified={setVerified}
      />
    </div>
  );
}

export default Main;

EDIT: Since I'm rendering the states in <Preview /> but setting the states in <Info /> where am (or should I) be saving to local storage.

Is there a way to save all these states at the same time every time one of them is set or is that not how saving states to local storage works. Also where and when exactly should I add them to local storage, as in, where does the function to add them go? Whenever the state is changed? Or at certain increments?

Yehuda
  • 27
  • 15
  • make them as object and then you can add to local storage, [check this](https://stackoverflow.com/questions/42020577/storing-objects-in-localstorage) for more.. – QuantumX Nov 22 '22 at 05:54

2 Answers2

4

You can Separately store all the states in different local variables

localStorage.setItem('thumb',thumb);

OR

Make an object containing all the variables you want to store in local storage, then serialize it using JSON.stringify method and store it in local storage.

let anObject={
  "thumb":thumb,
  "timestamp":timestamp,
  "channelPic":channelPic,
  "title":title,
  "channelName":channelName,
  "views":views,
  "timeAgo":timeAgo,
  "increment":increment,
  "verified":verified
};

localStorage.setItem('obj', JSON.stringify(anObject));

Then, to retrieve the item use JSON.parse

anObject=JSON.parse(localStorage.getItem('obj'));

After that to update the values you can call useEffect and then update the anObject and set it to local storage.

useEffec(()=>{
anObject={
      "thumb":thumb,
      "timestamp":timestamp,
      "channelPic":channelPic,
      "title":title,
      "channelName":channelName,
      "views":views,
      "timeAgo":timeAgo,
      "increment":increment,
      "verified":verified
    };

    localStorage.setItem('obj', JSON.stringify(anObject));
},[thumb,timestamp,channelPic,title,channelName,views,timeAgo,increment,verified])

You can even get the values at the time of page load and set the states with them.

let anObject={};
useEffect(()=>{
anObject=JSON.parse(localStorage.getItem('obj'));
setThumb(anObject.thumb);
setTimestamp(anObject.timestamp);
setChannelPic(anObject.channelPic);
setTitle(anObject.title);
setChannelName(anObject.channelName);
setViews(anObject.views);
setTimeAgo(anObject.timeAgo);
setIncrement(anObject.increment);
setVerified(anObject.verified);
},[]);

The syntax might be a little bit 'off'

kushagra-aa
  • 540
  • 5
  • 11
  • Where exactly am I putting all this? Where I set my states? I'm gonna edit my question to show more code. – Yehuda Nov 22 '22 at 14:57
  • 1
    I think you should set the values in localStorage in `Info` component where you are setting the states or in the `Main` component using `useEffect` OR if you have this many states and using them in multiple components, You might wanna think about using a state management library like [Redux](https://redux.js.org/) or [Recoil](https://recoiljs.org/) or [React Context Hook](https://reactjs.org/docs/context.html) – kushagra-aa Nov 23 '22 at 11:15
0

Ideally group related state

    const initialState = {
      timestamp: "1:20",
      title: "Title",
      channelName: "Channel",
      views: "1,000",
      timeAgo: "23",
      increment: "minute",
      verified: false
    }
    
    const state_key = 'GROUP_STATE'
    
    const SomeComponent = (props) => {
      const [groupedState, setGroupedState] = useState({ ...initialState })
     
      const setThumb = (thumb) => setGroupedState(s => ({ ...s, thumb }));
      const setTimestamp] = (timestamp) = setGroupedState(s => ({ ...s, timestamp }));
    
      useEffect(() => {
    
        localStorage.setItem(state_key, JSON.stringify(setThumb));
    
      }, [setThumb]) // save makes its easy

Hope it helps

Azzy
  • 1,717
  • 2
  • 13
  • 17