I'm doing a simple Todolist in react.js. So far I'm able to save my objects to LocalStorage, but when I refresh the page the Todo elements are disappearing.
import React, { useState,useEffect } from 'react'
import TodoList from './TodoList.jsx'
const AddTodo = () => {
const [newTodo, setNewTodo] = useState('')
const [list, setList] = useState([])
const handleSubmit = () => {
const todoItem = {
id:Math.floor(Math.random() * 10000),
value:newTodo
}
if(todoItem){
setList([...list,todoItem])
setNewTodo('')
}
/*gets the oldlist and whats inside of it and adds the new item */
console.log(list)
}
useEffect(() => {
localStorage.setItem("list", JSON.stringify(list));
}, [list])
useEffect(() => {
const data = JSON.parse(localStorage.getItem('list'));
if(data){
setList(data)
}
}, [])
return (
<div className="input_container">
<form onSubmit={(e) => e.preventDefault()}>
<input type="text"
onChange={e => setNewTodo(e.target.value)}
className="todo-input"
placeholder="Write Todo.."
value={newTodo}
name="text"/>
<button onClick={() => handleSubmit()} className="add-todo-button">
Add Todo
</button>
</form>
<TodoList list={list} newTodo={newTodo}/>
</div>
)
}
export default AddTodo