Building in Public – 5

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);
...
}
Enter fullscreen mode Exit fullscreen mode

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 🎉


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Grow with review tale.