This content originally appeared on DEV Community and was authored by Bryan Liao
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 🎉
This content originally appeared on DEV Community and was authored by Bryan Liao

Bryan Liao | Sciencx (2024-07-27T22:28:58+00:00) Building in Public – 5. Retrieved from https://www.scien.cx/2024/07/27/building-in-public-5/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.