skip to Main Content

I am using localStorage to store my data locally. I can see the defined object but when I add a value and then refresh the page, the new added data is lost and is not stored. What could be the problem?

https://codesandbox.io/s/todolistmax-9ng5fx?file=/src/App.js

This is the link to my codesandbox. After refresh, the newly entered data is lost and is not saved.

Thanks!

2

Answers


  1. First, you have a useEffect that is always firing and overriding the localStorage. Also, you should save modified course goal in localStorage every time you do an action:

    Bonus
    I reworked some of your modifying code (Codesandbox)

    import "./styles.css";
    import { useState, useEffect } from "react";
    import CourseList from "./components/CourseList";
    
    import CourseInput from "./components/CourseInput";
    const dummy_data = [
      {
        id: 1,
        text: "Do all React Exercises"
      },
      {
        id: 2,
        text: "Learn more Javascript"
      }
    ];
    
    export default function App() {
      const [courseGoal, setCourseGoal] = useState(dummy_data);
      console.log(courseGoal);
    
      useEffect(() => {
        const data = window.localStorage.getItem("MY_LIST_OF_GOALS");
        if (data) {
          console.log(JSON.parse(data));
          setCourseGoal(JSON.parse(data));
        }
      }, []);
    
      const setGoalsInLocalStorage = (goals) => {
        window.localStorage.setItem("MY_LIST_OF_GOALS", JSON.stringify(goals));
      };
    
      const addGoalHandler = (enteredText) => {
        setCourseGoal((prevGoal) => {
          const newArray = [enteredText, ...prevGoal]
          setGoalsInLocalStorage(newArray);
    
          return newArray;
        });
      };
    
      const deleteGoalHandler = (id) => {
        setCourseGoal((prevGoal) => {
          const updatedGoal = prevGoal.filter((goal) => goal.id !== id);
          setGoalsInLocalStorage(updatedGoal);
          return updatedGoal;
        });
      };
    
      return (
        <div className="App">
          <CourseInput onAddGoal={addGoalHandler} />
          <h1>Course List</h1>
          <CourseList items={courseGoal} onDelete={deleteGoalHandler} />
        </div>
      );
    }
    
    
    Login or Signup to reply.
  2. App.js

    The problem is that the useEffect hook that saves data to localStorage runs on every state change. To fix it, add an empty dependency array [] as the second argument to the useEffect hook that saves to localStorage. This ensures it runs only once on mount and won’t overwrite your data on subsequent updates.

    Without a dependency array, the useEffect hook will run after every render,

    so updated useEffect hook is

      useEffect(() => {
        const data = window.localStorage.getItem("MY_LIST_OF_GOALS");
        if (data) {
          setCourseGoal(JSON.parse(data));
        }
      }, []); // Empty dependency array ensures this runs only once on mount
    
      useEffect(() => {
        window.localStorage.setItem("MY_LIST_OF_GOALS", JSON.stringify(courseGoal));
      }, [courseGoal]); // Save to localStorage whenever courseGoal changes
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search