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…


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Building in Public – 5." Bryan Liao | Sciencx - Saturday July 27, 2024, https://www.scien.cx/2024/07/27/building-in-public-5/
HARVARD
Bryan Liao | Sciencx Saturday July 27, 2024 » Building in Public – 5., viewed ,<https://www.scien.cx/2024/07/27/building-in-public-5/>
VANCOUVER
Bryan Liao | Sciencx - » Building in Public – 5. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/27/building-in-public-5/
CHICAGO
" » Building in Public – 5." Bryan Liao | Sciencx - Accessed . https://www.scien.cx/2024/07/27/building-in-public-5/
IEEE
" » Building in Public – 5." Bryan Liao | Sciencx [Online]. Available: https://www.scien.cx/2024/07/27/building-in-public-5/. [Accessed: ]
rf:citation
» Building in Public – 5 | Bryan Liao | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.