How to Persist a Es6 Map in Localstorage (Or Elsewhere)

How do I persist a ES6 Map in localstorage (or elsewhere)?

Assuming that both your keys and your values are serialisable,

localStorage.myMap = JSON.stringify(Array.from(map.entries()));

should work. For the reverse, use

map = new Map(JSON.parse(localStorage.myMap));

persisting array state to local storage

LocalStorage stores key-value pairs. So to store a javascript object you need to serialize it with JSON.stringify(object => String) and to retrieve item from localStorage you need to convert to an object again with JSON.parse(String =>object)

So change addTask and componentDidMount like below:

  addTask = event => {
event.preventDefault();
let newTask = {
task: this.state.todo,
id: Date.now(),
completed: false
};
this.setState(
{
todos: [...this.state.todos, newTask],
todo: ""
},
() => {
localStorage.setItem("todos", JSON.stringify(this.state.todos));
}
);
};

componentDidMount() {
const todos = localStorage.getItem("todos");
if (todos) this.setState({ todos: JSON.parse(todos) });
}

Here is the temporary sandbox containing the fixed version

How can I persist localstorage when ComponentDidMount resets the value on refresh?

In case anyone has the same issue, I fixed this by checking if the value exists in local storage and using that value instead, or initializing it if it doesn't exist.

Like so:

if(JSON.parse(localStorage.getItem(category)) !== null || undefined ) {
news = JSON.parse(localStorage.getItem(category));
} else {
news = news.map((x) => ({ ...x, likes: 0 }));
}


Related Topics



Leave a reply



Submit