Skip to content
Related Articles

Related Articles

How to save new state to local JSON using ReactJS ?
  • Difficulty Level : Hard
  • Last Updated : 14 Apr, 2021

Sometimes we need to store the state locally on the browser in a JSON format. We can save any information to the local storage of the browser and access that information anytime later.

Setting up environment and Execution:

  • Step 1: Create React App by using the following command.

    npx create-react-app foldername
  • Step 2: After creating your project folder, i.e., folder name, move to it using the following command:

    cd foldername
>

Project Structure: It will look like the following.



App.js

import React, { Component }  from 'react';
  
class App extends Component {
  
  state = {
    data: "This is data",
    num: 123,
    boolean: true,
  }
  
  // save data to localStorage
  saveStateToLocalStorage = () => {
    localStorage.setItem('state', JSON.stringify(this.state));
  }
  
  // Fetch data from local storage
  getStateFromLocalStorage = () => {
    let data = localStorage.getItem('state');
    if(data !== undefined) {
      this.setState(JSON.parse(data));
    }
  }
  
  componentDidMount() {
    // Fetch data from local storage
    this.getStateFromLocalStorage();
  }
  
  render() {
    return (
      <div>
        <h2>GeeksforGeeks</h2>
        <button onClick={this.saveStateToLocalStorage}>
          Save State to local storage\
        </button>
      </div>
    );
  }
}
  
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.

My Personal Notes arrow_drop_up
Recommended Articles
Page :