-1

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

2 Answers2

0

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.

Duc Hong
  • 1,149
  • 1
  • 14
  • 24
  • Yes it work but if we want list of objects I means how to store all the todos in local storage and then fetch all them how it is possible – deeno james May 13 '20 at 05:32
  • the storing idea is the same, first you need to have a complete list of Todos, usually this is an array, then calling `JSON.stringify` this to store into your localStorage. If you want to retrieve this data, just `JSON.parse` like you did, but now it's an array of Todos, not just one single object. – Duc Hong May 13 '20 at 05:46
  • `localStorage` just plays as a cache layer here, you can store whatever you want, since the accepted format is just STRING. No wonder you need to `stringify` the data first before storing, and `parse` before actually using it – Duc Hong May 13 '20 at 05:50
  • how to do it and where put it – deeno james May 13 '20 at 06:06
  • this is out of the context we're discussing, are you developing this or just maintaining from another developer ? – Duc Hong May 13 '20 at 06:08
0

Based on information available, below code will work -

onNewTaskClickHandler = () => {
this.setState((prevState) => ({
    todos: [].concat(prevState.todos).concat(JSON.parse(localStorage.getItem('todos')))
}));
}
Durgesh
  • 205
  • 2
  • 9