Home > database >  React useState doesnt update from localstorage
React useState doesnt update from localstorage

Time:05-11

When i try to use setTodos(storedTodos) it just resets the array. if i replace the const [todos, setTodos] = useState([]); with const [todos, setTodos] = useState(JSON.parse(localStorage.getItem('todos'))); it works but only when theres already data in the array so when i clear the site data or open the page for the first time it just crashes.

heres my complete code:

import './App.css';

import Form from './components/Form.js';
import ToDoList from './components/ToDoList';


function App() {

  //States
  const [inputText, setInputText] = useState("");
  const [inputTime, setInputTime] = useState("");
  const [todos, setTodos] =  useState([]);   //(JSON.parse(localStorage.getItem('todos')));
  const [status, setStatus] = useState("all");
  const [filteredTodos, setFilteredTodos] = useState ([]);

  useEffect(() => {
    var storedTodos = JSON.parse(localStorage.getItem('todos'));
    setTodos(storedTodos);
  }, []);

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

  //Functions
  const filterHandler = () => {
    switch(status){
      case 'completed':
        setFilteredTodos(todos.filter(todo =>todo.completed === true))
        break;
      case 'uncompleted':
        setFilteredTodos(todos.filter(todo =>todo.completed === false))
        break;
      default:
        setFilteredTodos(todos);
        break;
    }
  };

const getLocalTodos = () => {
  var storedTodos = JSON.parse(localStorage.getItem('todos'));
  setTodos(storedTodos);
};

//save the list localy
const saveLocalTodos = () => {
  console.log("save");
  console.log(todos);
   localStorage.setItem('todos', JSON.stringify(todos));
   console.log(todos);
};

  return (
    <div className="App">
      <Form 
        inputText={inputText}
        inputTime={inputTime}
        setInputText={setInputText}
        setInputTime={setInputTime}

        todos={todos} 
        setTodos={setTodos}  
        setStatus={setStatus}
      />
      <ToDoList 
        setTodos={setTodos} 
        todos={todos}
        filteredTodos={filteredTodos}
      />
    </div>
  );
}

export default App;```

CodePudding user response:

Try this method using Logical OR operator.

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