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 :)
You need to add it to the existing todo
array from local storage. Something like this:
export const setLocalStorage = (item) => {
const todo = JSON.parse(localStorage.getItem('todo'));
todo.push(item);
localStorage.setItem('todo', JSON.stringify(todo));
}
It is good to save it as an array each time when you enter a new data.
localStorage.util.js
export const setItemToLocalStorage = (key, item = []) => {
localStorage.setItem(key, JSON.stringify(item));
}
export const getItemFromLocalStorage = (key) => {
return JSON.parse(localStorage.getItem(key));
}
component
constructor(props) {
super(props)
initData();
}
const initData = () => {
this.setState({
todo: '',
todoList: getItemFromLocalStorage('todoList') || []
});
}
const saveLog = (e) => {
e.preventDefault();
setLocalStorage('todoList', [...this.state.todoList, this.state.todo]);
initData();
}
function saveTodo(newTodo) {
try {
const key = "todos";
// Get todos from the storage
const value = window.localStorage.getItem(key);
let todos = [];
if (value !== null) {
// Parse the result into JSON
todos = JSON.parse(value);
}
// Push new todo in the list
todos[todos.length] = newTodo;
// Save the result to the storage
window.localStorage.setItem(key, todos);
} catch (error) {
// Log error
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.