How to get item from local storage?

Viewed 366

I am making a todo list app with react.

I'm trying to adding todos to local storage but I'm stuck in the getItem part. I don't know where to put.

Right now, showing in local storage section but when I refresh the page it is not showing in todolist section.

function App() {

 const [change, setChange] = useState();

 const [todos, setTodos] = useState([]);

 useEffect(() => {
   console.log(todos);

 });

 const ChangeValue = (e) => {
   setChange(e.target.value);
 };

 const AddTodo = (e) => {

   const TodoId = Math.floor(Math.random() * 10000) + 1

   const newTodo = { content: change, id: TodoId }

   localStorage.setItem('todoInLocalStorage',change);


   setTodos((oldTodos) => [...oldTodos, newTodo]);

   e.preventDefault()
 };

 const DeleteButton = (id) => {
   setTodos(todos.filter((item)=> item.id !== id));
 };

 const DeleteAll = () => {
   setTodos([]);
 };

 return (
   <div className="App">
     <div className="frame">
       <h1>To Do List</h1>
       <FormInput ChangeValue={ChangeValue} AddTodo={AddTodo}/>
       <div className="card-2">
         <h2><u>To Do's</u></h2>
         <div className="todos">
            <Todos todos={todos} DeleteButton={DeleteButton}/>
         </div>
       </div>
       <button onClick={DeleteAll} className="ClearTodo">
         Clear All To Do
       </button>
     </div>
   </div>
 );
}
5 Answers

I would suggest doing something like this:

Every time your todos changes, have a useEffect that saves it to the localStorage. As for initialization, just use it as the initial value of useState for todos

There are three things you need to do:

  1. Add

    useEffect(() => {
      localStorage.setItem('todos', JSON.stringify(todos));
    }, [todos])
    
  2. Remove any other localStorage.setItem call outside of this useEffect (because the todos state will be automatically saved to localStorage every time it changes)

  3. Initialize your todos state like so:

    const [todos, setTodos] = useState(JSON.parse(localStorage.getItem('todos')) || []);
    

    That way, the initial value will be either what you saved, or if it doesn't exist will default to an empty array.

You should definitely add it while initializing the todo in the useState call like this:

const [todos, setTodos] = useState(localStorage.getItem('todoInLocalStorage') ? localStorage.getItem('todoInLocalStorage') : []);

In the above code we are first checking if there's any todo present in localstorage, If not we are assigning the default value as empty array.

function App() {

 const [change, setChange] = useState();

const [todos, setTodos] = useState(localStorage.todoInLocalStorage ?localStorage.todoInLocalStorage : [] );

 useEffect(() => {
   console.log(todos);

 });

 const ChangeValue = (e) => {
   setChange(e.target.value);
 };

 const AddTodo = (e) => {

   const TodoId = Math.floor(Math.random() * 10000) + 1

   const newTodo = { content: change, id: TodoId }

   localStorage.setItem('todoInLocalStorage',change);


   setTodos((oldTodos) => [...oldTodos, newTodo]);

   e.preventDefault()
 };

 const DeleteButton = (id) => {
   setTodos(todos.filter((item)=> item.id !== id));
   localStorage.todoInLocalStorage(todos.filter((item)=> item.id !== id));
 };

 const DeleteAll = () => {
   setTodos([]);
   localStorage.removeItem('todoInLocalStorage')
 };

 return (
   <div className="App">
     <div className="frame">
       <h1>To Do List</h1>
       <FormInput ChangeValue={ChangeValue} AddTodo={AddTodo}/>
       <div className="card-2">
         <h2><u>To Do's</u></h2>
         <div className="todos">
            <Todos todos={todos} DeleteButton={DeleteButton}/>
         </div>
       </div>
       <button onClick={DeleteAll} className="ClearTodo">
         Clear All To Do
       </button>
     </div>
   </div>
 );
}

You will have to do JSON.parse(localStorage.getItem('todos'))

localStorage.getItem('keyWhichYouSetInLocalStorage')
Related