I am trying to use a LocalStorage so that every time I add a new task it adds to localstorage but at the moment it always overwritten the original one.
I have a wrapper for LocalStorage:
export const setLocalStorage = (item) => {
localStorage.setItem('todo', JSON.stringify(item));
}
Then I have a React component where I import the wrapper, I have a simple form in that component with one input field and a button:
<Button onClick={(e) => { saveTodo(e) }}> Save Changes </Button>
saveTodo function:
constructor(props) {
super(props)
this.state = {
todo: '',
}
}
const saveLog = (e) => {
e.preventDefault();
setLocalStorage(this.state.todo);
}
Now every time I execute the function it by hitting the button the LocalStorage get overwritten by the new value, but I want to keep adding onto the local storage
How can I achieve this?
This is what i have done so far:
export const setLocalStorageItem = (todo) => {
var todoList = JSON.parse(localStorage.getItem('todo')) || [];
console.log(todoList);
todoList.push(todo)
localStorage.setItem('todo', JSON.stringify(todoList));
}
I have added two items to localsotage:
Storage {todo: "["hello","123"]", length: 1}
length: 1
todo: "["hello","123"]"
__proto__: Storage
So it works perfect now :)