简体   繁体   中英

how to save react js state into localstorage

I have no idea How to store the react js state into localstorage.

import React, { Component } from 'react'
import './App.css';
import { auth,createUserProfileDocument } from './firebase/firebase.utils'
import { TodoForm } from './components/TodoForm/TodoForm.component'
import {TodoList} from './components/TodoList/TodoList.component'
import {Footer} from './components/footer/footer.component'
import Header from '../src/components/header/header.component'
import {Redirect} from 'react-router-dom'

import {connect} from 'react-redux'
import {setCurrentUser} from './redux/user/user.actions'

export class App extends Component {
  constructor(props) {
    super(props)

    this.input=React.createRef()
    this.state = {
        todos:[
         {id:0, content:'Welcome Sir!',isCompleted:null},
        ]


    }
  }

  todoDelete = (id) =>{
    const todos = this.state.todos.filter(todo => {
      return todo.id !== id 
    })
    this.setState({
      todos
    })
  }
   toDoComplete = (id,isCompleted) =>{
     console.log(isCompleted)
     var todos = [...this.state.todos];
     var index = todos.findIndex(obj => obj.id === id);
     todos[index].isCompleted = !isCompleted;
     this.setState({todos});
     console.log(isCompleted)
      }

  addTODO = (todo) =>{
         todo.id = Math.random()
         todo.isCompleted = true
         let todos = [...this.state.todos, todo]
         this.setState({
           todos
         })
  }


 unsubscribeFromAuth = null;

 componentDidMount() {
  const { setCurrentUser } = this.props;

  this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
    if (userAuth) {
      const userRef = await createUserProfileDocument(userAuth);

      userRef.onSnapshot(snapShot => {
        setCurrentUser({
          id: snapShot.id,
          ...snapShot.data()
        });
      });
    }

    setCurrentUser(userAuth);
  });
}

componentWillUnmount() {
  this.unsubscribeFromAuth();
}

  render() {
    return (

      <div className='App'>
            <Header />
            <TodoForm addTODO={this.addTODO} />
            <TodoList 
              todos={this.state.todos} 
              todoDelete={ this.todoDelete} 
              toDoComplete={ this.toDoComplete}
           />
            <Footer/>
      </div>
    )
  }
}

const mapStateToProps = ({ user }) => ({
  currentUser: user.currentUser
});

const mapDispatchToProps = dispatch => ({
  setCurrentUser: user => dispatch(setCurrentUser(user))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

in my input Form


import './TodoForm.style.css'
export class TodoForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
             content : ''
        }
    }
    handleChange = (e) =>{
        this.setState({
            content: e.target.value
        })
    }
    handleSubmit =(e) =>{
        e.preventDefault();
        this.props.addTODO(this.state);
        this.setState({
            content: ''
        })
    }
    render() {
        return (
            <div className='inputTask'>
                <form onSubmit={ this.handleSubmit}>

                    <input 
                    className="textBox" 
                    type='text' 
                    onChange={ this.handleChange} 
                    value={this.state.content}
                    placeholder='what you want to do ...'
                    />
                </form>
            </div>
        )
    }
}

export default TodoForm

I have no idea How to store the react js state into localstorage. i searched on internet but unable to find the exact solution all the codes that i think is necessary post.

You can use reactLocalStorage to save any data in local storage

import {reactLocalStorage} from 'reactjs-localstorage';

reactLocalStorage.set('var', true);
reactLocalStorage.get('var', true);
reactLocalStorage.setObject('var', {'test': 'test'});
reactLocalStorage.getObject('var');
reactLocalStorage.remove('var');
reactLocalStorage.clear();

Read out the localStorage item in the componentDidMount callback. Simply read the item you want to get, check if it exists and parse it to a usable object, array or datatype that need. Then set the state with the results gotten from the storage.

And to store it, simply handle it in an event handler or helper method to update both the state and the localStorage item.

class ExampleComponent extends Component {

  constructor() {
    super();
    this.state = {
      something: {
        foo: 'bar'
      }
    }
  }

  componentDidMount() {
    const storedState = localStorage.getItem('state');
    if (storedState !== null) {
      const parsedState = JSON.parse(storedState);
      this.setState({ something: parsedState });
    }
  }

  clickHandler = (event) => {
    const value = event.target.value;
    const stringifiedValue = JSON.stringify(value);
    localStorage.setItem('state', stringifiedValue);
    this.setState({ something: value });
  }

  render() {
    return (
      <button onClick={clickHandler} value={this.state.something}>Click me</button>
    );
  }

}

Set data in localStorage

key-value pair:

localStorage.setItem('key_name',"value");

object

localStorage.setItem('key_name', JSON.stringify(object));

Remove data from localStorage

localStorage.removeItem('key_name');

Get data from localStorage

 let data = localStorage.getItem('key_name');

object:

let data = JSON.parse(localStorage.getItem('key_name'));

clear localStorage (delete all data)

localStorage.clear();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM