Home > Software design >  Why is localStorage getting cleared whenever I refresh the page?
Why is localStorage getting cleared whenever I refresh the page?

Time:05-13

Like the title says, the localStorage I set registers the changes made to the todoList array and JSON.stringifys it; however, whenever I refresh the page the array returns to the default [] state.

const LOCAL_STORAGE_KEY = "task-list"

function TodoList() {
    const [todoList, setTodoList] = useState([]);

    useEffect(() => {
        const storedList = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
        if (storedList) {
            setTodoList(storedList);
        }
    }, []);
    
    useEffect(() => {
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todoList));
    }, [todoList]);

CodePudding user response:

When you reload the app/component both effects will run, and React state updates are processed asynchronously, so it's picking up the empty array state persisted to localStorage before the state update is processed. Just read from localStorage directly when setting the initial todoList state value.

Example:

const LOCAL_STORAGE_KEY = "task-list"

function TodoList() {
  const [todoList, setTodoList] = useState(
    JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || []
  );
    
  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todoList));
  }, [todoList]);

  ...

Edit why-is-localstorage-getting-cleared-whenever-i-refresh-the-page

  • Related