ReactJS is a powerful JavaScript library for building user interfaces, and it provides developers with various tools and techniques to manage application state. One common requirement in many applications is to save and persist state data. In this article, we will explore how to save new state to a local JSON file using ReactJS.
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
Javascript
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>neveropen</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.