Building in Public - 5
Posted On: 2024-07-27
I added the use of localStorage to my React project. Since my app is client-only, it felt like the right thing to do to allow some data persistence.
I created two functions: one to load data from localStorage and another one to add data. The key-value pairing in localStorage is just strings, so I had to use JSON.stringify() and JSON.parse() to manipulate the data:
const context = {...};
localStorage.setItem('appData', JSON.stringify(context));
const localData = localStorage.getItem('appData');
if(localData){
const parsedData = JSON.parse(localData);
...
}
Initially I was calling the add data function in my form submissions, but since I was using React I found it easier to use stick it in useEffect instead. Using the existing data as a dependency, I could update localStorage any time it changed.
I also called my data loading function within useEffect. I used useRef to determine the first render in order to swap between loading previously saved data and updating localStorage when the data changed. Hooray for data persistence 🎉