Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React useState doesnt update from localstorage

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;```

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this method using Logical OR operator.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading