Search code examples
javascriptreactjsreact-reduxlocal-storagetodomvc

how to setState the data from localstorage into an array of object in React js


this is my setState in APP.js

this.state = {
       todos:[
        {id:0, content:'Welcome Sir!',isCompleted:true},

       ]
    }
  }

here I fetched the data from local srorage

    this.documentData = JSON.parse(localStorage.getItem('todos'));


}

I fetched the data from localstorage but confused how to store it into State the data fetch in format {content: "dd",id: 0.10599785413372431,isCompleted: true} note that this is a todo app so every time we create a task means we create an object


Solution

  • As your localStorage was just one object of To-do. I think you can try this to set new data into your array of objects:

    this.setState( prevState => ({
      todos: [
        ...prevState.todos,
        JSON.parse(localStorage.getItem('todos'))
      ]
    }))
    

    Notice that this assumes you're writing component as Class.