[SOLVED] How to react keep the data in Localstorage and show

Issue

This Content is from Stack Overflow. Question asked by Büşra FERŞADOĞLU

I made a simple todo app with React, but I can keep the data in localstorage but I can’t display it. How cani fix this?



Solution

I use your code and remove status, filteredHandler() because they are not define. Then , code work

Code:

import React, {useEffect,useState} from 'react';

export function App(props) {
    const [todos, setTodos] = useState([]);
    useEffect(() => {
    getLocalTodos();
  }, [])

  useEffect(() => {
    saveLocalTodos();
  }, [todos]);

  const saveLocalTodos = () => {
    localStorage.setItem("todos", JSON.stringify(todos));
  }
  const getLocalTodos = () => {
    if(localStorage.getItem("todos") === null){
      localStorage.setItem("todos", JSON.stringify([]));
    }
    else{
      let todoLocal = JSON.parse(localStorage.getItem("todos"));
      setTodos(todoLocal)
    }
  }

  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen! {todos[0]}</h2>
    </div>
  );
}

Demo: enter image description here

Review your code, I think your saveLocalTodos, getLocalTodos functions have no problem…


This Question was asked in StackOverflow by Büşra FERŞADOĞLU and Answered by Kyn It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?