How to persist data to localStorage in React with hooks.

Gautham Vijayan - Dec 8 '20 - - Dev Community

In my previous post I shared my new react project where I used data visualization with pie chart in my app in a small scale.

I should have made a backend server but instead I used localStorage to satisfy all my needs.

In this post I will discuss how you can have persistent data in your localStorage in react with hooks.

What is persistent data?

In a react app if you reload the page, all the state vanishes.

If you want to push an array of object to localStorage with useState and getting all sorts of errors like state vanishing after the page loading, you are at the right place because I solved this issue and deployed my react-project which uses React hooks+localStorage.

This post focusses on pushing array of objects into localStorage without getting any errors.chrome-capture (33)

In order to tackle this issue, we can use useEffect to our advantage.

We are going to use not one but two useEffect hooks in our app.

Ok let me first explain what we are going to do.

We are going to create a react app which will get data from the user and send array of objects to the localStorage and map it and display its elements in the frontend like my project.

Alt Text
Ok lets get the boilerplate done.


import React, { useState,useEffect } from 'react';
const Form = () => {
  const [name, setname] = useState('')
  const [price,setprice]=useState('')
  const [item,setitem]=useState([]) 

const handleSubmit = (e) => {

    e.preventDefault();
    setitem([...item,{name:name,price:price}])
    setname('')
    setprice('')

  };

return(
<form onSubmit={handleSubmit}>

<input type = "text" name="name" value={name} onChange={(e) => setname(e.target.value)}/>

<input type = "number" name="price" value={price} onChange={(e) => setprice(e.target.value)}/>

<input type = "submit"/>

</form>
)
Enter fullscreen mode Exit fullscreen mode

Now here comes the useEffect part.

We will be using two useEffect hooks in here to store array of object data into localStorage and fetching it to show it in the frontend.

The first useEffect hook will get the items from localStorage and set it to the 'item' useState array when the page first loads.

Then the second useEffect hook will set the items to localStorage whenever the state (that is the item) changes.


useEffect(()=>{

const data = localStorage.getItem('data')

if(data){
  setitem(JSON.parse(data))
 }

},[])

useEffect(()=>{

  localStorage.setItem('data',JSON.stringify(item))

})

Enter fullscreen mode Exit fullscreen mode

If you execute this perfectly you can now access localStorage as a database to get and post data to it like I did in my project.

The only downside to this is all the elements are stored as JSON strings and you need some ways to get over this with parseInt().

And that's how you can use React Hooks with localStorage to make a database within the browser itself.

To know more about React & React Native you can checkout my courses in Udemy.

https://www.udemy.com/course/react-native-for-absolute-beginners-with-react-hooks/

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player