Open In App

How to save new state to local JSON using ReactJS ?

Improve
Improve
Like Article
Like
Save
Share
Report

To save data in local storage is a common task while creating a react application to store the user-specific data. We can save new state to local JSON using react in local storage of the browser and access that information anytime later.

Prerequisites:

Approach:

In React to save a new state to local JSON we will use the localStorage web API. localStorage API helps to access the storage of the browser to store and manage data. This data may be used for user-specific settings and configuration when the web page is visited.

Steps to create React Application:

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:

Example: This example uses localStorage API to set the json data in local storage.

Javascript




// Filename - 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.



Last Updated : 10 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads