I have tried to create a Todo List and also I have used local storage key but still it doesn't store my todos. The problem is everytime is refresh it, all todos are gone.I want to know what's the problem is? What should I do for this? Here is my code:
import React, { useState, useRef, useEffect } from "react";
import TodoList from "./TodoList"
const { v4: uuidv4 } = require('uuid');
const LOCAL_STORAGE_KEY = 'todoApp.todos'
function App() {
const [todos, setTodos] = useState([])
const doAccess = useRef()
useEffect(() => {
const storedTodos = JSON.parse (localStorage.getItem(LOCAL_STORAGE_KEY))
if (storedTodos) setTodos(storedTodos)
}, [])
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos))
}, [todos])
function toggleTodo(id){
const newTodos = [...todos]
const todo = newTodos.find(todo=> todo.id === id)
todo.complete =!todo.complete
setTodos(newTodos)
}
function handleAddTodo(e){
const name= doAccess.current.value
if (name === '') return
setTodos (prevTodos =>{
return [...prevTodos, {id: uuidv4(), name: name, complete: false}]
})
}
return (
<>
<TodoList todos={todos} toggleTodo={toggleTodo}/>
<input ref={doAccess} type="text" />
<button onClick={handleAddTodo}>Add Todo</button>
<button>Clear Todo</button>
<div>0 Todos Left</div>
</>
)
}
export default App;
CodePudding user response:
use the refresh button and it'll reflect all the changes.
CodePudding user response:
useEffect
in React if given any variables in []
will execute at the component mount and variable change. So as per your code it is performing localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos))
at the component mount in which todos
variable will not be set immidiately by the first useEffect
.
Include console.log
like the below code for your understanding.
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos));
console.log("setting", todos);
}, [todos]);
Solution:
Remove the given use effect and try to set the local storage in the function where the todos
state gets updated.