I'm having problems to persist the state in the local storage. It's a simple todo app. After adding one todo and refreshing it, all todos are being deleted. Could not figure out why. Here is the relevant code:
const [ todos, setTodos ] = useState([])
useEffect(() => {
│ │ console.log('b1:',JSON.parse(localStorage.todos))
│ │ if (localStorage.todos !==null) {
│ │ │ console.log(JSON.parse(localStorage.todos))
│ │ │ setTodos(JSON.parse(localStorage.todos))
│ │ }
│ │ console.log('a1:',JSON.parse(localStorage.todos))
│ }, [])
│ useEffect(() => {
│ │ // if (todos.length > 0) {
│ │ │ console.log('b2:',JSON.parse(localStorage.todos))
│ │ │ localStorage.setItem("todos", JSON.stringify(todos))
│ │ │ console.log('a2:',JSON.parse(localStorage.todos))
│ │ // }
│ }, [todos])
console output (b1 before1, a1 after1 etc):
[Log] b1: – [{text: "one", done: false, id: "6c570584b1a"}] (1)
[Log] [{text: "one", done: false, id: "6c570584b1a"}] (1)
[Log] a1: – [{text: "one", done: false, id: "6c570584b1a"}] (1)
[Log] b2: – [{text: "one", done: false, id: "6c570584b1a"}] (1)
[Log] a2: – [] (0)
[Log] b1: – [] (0)
[Log] [] (0)
[Log] a1: – [] (0)
[Log] b2: – [] (0)
[Log] a2: – [] (0)
[Log] b2: – [] (0)
[Log] a2: – [] (0)