Reputation: 117
I'm trying to save items in local storage as array of objects. At first it works perfectly and stores first element in localstorage as I need, but I can't store more than one element.
Here is the code block initiates the local storage.
In this block I'm receiving an item as object from different component and assigning an ID to it. Afterwards, I update the state and store this object.
const saveEdit = (obj) =>{
const text = obj.article;
const id = Date.now().toString(36) + Math.random().toString(36).substr(2);
let article = { id: id, text:text}
setSavedArticles([...savedArticles,article])
localStorage.setItem('article', JSON.stringify(savedArticles));
}
I'm sending information from another component with onClick function.
<button
onClick={() => saveEdit({
article: textArea.current.value
})}
className="button mt-4">
Save
</button>
Upvotes: 0
Views: 349
Reputation: 867
The problem is that setting state in React is an asynchronous process. It means, that you save the previous value of savedArticles, not the updated one. You should make a new variable like this:
const newArticles = [...savedArticles,article]
And then update the state and local storage:
setSavedArticles(newArticles)
localStorage.setItem('article', JSON.stringify(newArticles));
Upvotes: 5
Reputation: 1484
savedArticles is not updated immediately since react updates state async.
const saveEdit = (obj) =>{
const text = obj.article;
const id = Date.now().toString(36) + Math.random().toString(36).substr(2);
let article = { id: id, text:text}
const newSavedArticles = [...savedArticles,article]
setSavedArticles(newSavedArticles )
localStorage.setItem('article', JSON.stringify(newSavedArticles ));
}
Upvotes: 2