skip to Main Content

i have a todolist, but i want de data to stand in the page when i reload. Im trying to work with local storage but im having problems with it. Im using setItem and getItem, but it isn`t working.

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

  useEffect(() => {
    const data = window.localStorage.getItem("todoStorage");
    setTodos(JSON.parse(data));
  }, []);

  useEffect(() => {
    window.localStorage.setItem("todoStorage", JSON.stringify(todos));
  }, [todos]);

2

Answers


  1. Chosen as BEST ANSWER

    well guys, i found an indian youtuber that helped me with that, im gonna post the code that fix that problem for me:

       const getLocalStorage = () => {
      let todos = localStorage.getItem("todos")
      if(todos) {
        return (todos = JSON.parse(localStorage.getItem("todos")))
      } else {
        return []
      }
    }
    
    function App() {
      const [todos, setTodos] = useState(getLocalStorage);
    
     useEffect(() => {
      localStorage.setItem("todos", JSON.stringify(todos))
     }, [todos])
    

  2. The issue you’re experiencing could be related to the initial state of the todos array. When the component is first rendered, the useEffect that reads from localStorage runs, and if there is no data in localStorage, it sets todos to null (since JSON.parse(null) results in null).

    To fix this issue, you can add a check to see if the data retrieved from localStorage is not null before setting the state. If it’s null, you can initialize todos to an empty array. Here’s how you can modify your code:

    const [todos, setTodos] = useState([]);
        
    useEffect(() => {
      const data = window.localStorage.getItem("todoStorage");
      if (data) {
        setTodos(JSON.parse(data));
      }
    }, []);
    
    useEffect(() => {
      window.localStorage.setItem("todoStorage",JSON.stringify(todos));
    }, [todos]);
    

    In this modified code, if the data retrieved from localStorage is not null, it will set the todos state with the parsed data. If the data is null, it will keep todos as an empty array. This way, even if there is no data in localStorage, todos will always be initialized as an empty array, preventing unexpected behavior when you reload the page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search