Asan
Asan

Reputation: 11

How to add items to localstorage in react?

I have tried implementing and adding data into local storage and it does not adding instead it keeps on updating the old one .can anyone say that how to add array of objects entered by user , so that it can be stored in the localstorage in react js?

Upvotes: 1

Views: 2914

Answers (1)

Anuja
Anuja

Reputation: 1038

You'll have to set the whole object at once;

const items = JSON.parse(localStorage.getItem("myItems"));
const newItems = JSON.stringify([...items,{name:"new item"}])
localStorage.setItem("myItems",newItems);

Upvotes: 3

Related Questions