Çetin
Çetin

Reputation: 117

Cannot save more than 2 items in localStorage

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

Answers (2)

Konstantin Samarin
Konstantin Samarin

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

Bjorne
Bjorne

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

Related Questions