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
How to Access Parent Window Object Using Jquery
Downloading Canvas Element to an Image
How to Ignore User's Time Zone and Force Date() Use Specific Time Zone
Password-Check Directive in Angularjs
Dynamic Extension Context Menu That Depends on Selected Text
How to Round Float Numbers in JavaScript
Differences Between Contenttype and Datatype in Jquery Ajax Function
JavaScript Custom Event Listener
Deep Copy an Array in Angular 2 + Typescript
What the Difference Between .Click and .Change on a Checkbox
How to Use Node.Js Module System on the Clientside
Appending Array to Formdata and Send via Ajax
Call a Vue.Js Component Method from Outside the Component
React.Js Replace Img Src Onerror
How to Open a Popup with JavaScript and Then Detect When the User Closes It