How to save data in react js ?.

React is a Javascript Framework and it work in frontend. Many times we need to persist the state of application in front end, this article will explain how to persist state of React application or save data in React application. For storing data in backend we have database, when we start a request from react application to backend to get some data from backend then response can be stored in Components state. But Component state become more complex in case of inter component communication. For this React have simplified solution to store data in native local storage of browser. There is no external package or library needed for this. React have local storage and session storage to store data in browser.

1. Local Storage :

Keyword localStorage is used for local storage. Browser compatibility can be checked from official page Official Local Storage .

It’s very easy to use , as localStorage variable available in react without importing any library. It has four built in Function to store, retrieve and remove data.

-> To store value , it has setter function

localStorage.setItem("key","value");

Here here ‘key’ is key to store and retrieve data and ‘value’ is data. Data must be in string format, if there is JSON object then that needs to be convert in string. Below is an example:

class App extends React.Component {
 constructor(props) {
   super(props);
   this.state = { 
            val: localStorage.getItem('key'),
       }
 }
save=(e)=>{
 localStorage.setItem("key", this.state.val);
 alert('Saved');
} 
render(){
 return ( 
   <div className="App"> 
        <input type="text" value={this.state.val} 
               onChange={(event)=>{ 
               this.setState({val:event.target.value});
               } }
        /> 
       <button onClick={this.save}>Save</button>
  </div> 
 );
}
}

-> To get value, it has getter function e.g.

 localStorage.getItem("key");

here key is the name which is used in storing data.JSON string need to parse in JSON object. Below is example:

class App extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
      val: localStorage.getItem('key'),
    }
  }
save=(e)=>{
 localStorage.setItem("key", this.state.val);
 alert('Saved');
}
show=(e)=>{
 let value = localStorage.getItem("key");
 this.setState({val:value});
 alert('Stored value is ' + value);
}
render(){
  return (
    <div className="App">
         <input type="text" value={this.state.val}
                onChange={(event)=>{
                      this.setState({val:event.target.value});
                      } }
          />
        <button onClick={this.save}>Save</button>
        <button onClick={this.show}>Retrieve</button> 
    </div>
  );
}
}

-> To remove data, it two function(localStorage.removeItem(‘key’) and localStorage.clear())

To remove specific data then use localStorage.removeItem(‘key’).
To remove all data then use localStorage.clear().

Below is complete example of local storage.

class App extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
       val: localStorage.getItem('key'),
    }
  }
save=(e)=>{
    localStorage.setItem("key", this.state.val);
    alert('Saved');
}
remove=(e)=>{
    localStorage.removeItem("key");
    alert('Removed');
}
show=(e)=>{
  let value = localStorage.getItem("key");
  this.setState({val:value});
  alert('Stored value is ' + value);
}
render(){
return ( 
   <div className="App">   
      <input type="text" value={this.state.val}
             onChange={(event)=>{
                   this.setState({val:event.target.value}); 
                   } }
      />
     <button onClick={this.save}>Save</button>
     <button onClick={this.remove}>Remove</button>
     <button onClick={this.show}>Retrieve</button>
   </div> 
 );
}
}

Local Storage data will persist always even after closing browser. When we open browser then data will be there browser. You can find its source code from github Local Storage repository .

2. Session Storage :

Keyword sessionStorage is used for session storage. Browser compatibility can be checked from official page official session storage.

It is same as local storage, only the difference is that it has the expiration of data. Saved data will be empty on closing the browser however there will no intact on refreshing or tab closing. Session storage is have same function as of local storage. Source Code is available on GitHub
Below is the example of Session Storage.


class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      val: sessionStorage.getItem('key'),
    }
  }
	
save=(e)=>{
   sessionStorage.setItem("key", this.state.val);
   alert('Saved');
}

remove=(e)=>{
  sessionStorage.removeItem("key");
  alert('Removed');
}

show=(e)=>{
  let value = sessionStorage.getItem("key");
  this.setState({val:value});
  alert('Stored value is ' + value);
}
render(){
  return (  
   <div className="App">
      <input type="text" value={this.state.val}
             onChange={(event)=>{ 
                this.setState({val:event.target.value});
                } }
       /> 
     <button onClick={this.save}>Save</button>
     <button onClick={this.remove}>Remove</button>
     <button onClick={this.show}>Retrieve</button>
  </div>
 );
}
}

Learn React js tutorial for beginners

1 reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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