0

I'm making an advent calendar in React and using localStorage so the opened doors remain open when the user return the next day.

I am able to write to and read the localStorage but the first time the user clicks on the door it is not added, it adds it to the openedArr array but not localStorage, I'm sure I'm missing something simple but cannot see it! here is my code..

  const localData = localStorage.getItem("openDoors");
  const [openedArr, setOpenedArr] = useState(localData ? localData : []);
  const openDoor = e => {
    e.currentTarget.parentElement.classList.add("opened");
    setOpenedArr([...openedArr, e.currentTarget.id]);
    localStorage.setItem("openDoors", openedArr);
  };

2 Answers 2

6

The value you are setting is not the same as the value you add to local storage.

Try something like this:

const openDoor = e => {
    e.currentTarget.parentElement.classList.add("opened");
    const newValue = [...openedArr, e.currentTarget.id];
    setOpenedArr(newValue);
    localStorage.setItem("openDoors", JSON.stringify(newValue));
  };
Sign up to request clarification or add additional context in comments.

1 Comment

you also need to stringify value
2

Everything is saved as string in localstorage. You need to update stringify/parse value when you save/load from localstorage.

...
const localData = JSON.parse(localStorage.getItem("openDoors"));
...
localStorage.setItem("openDoors", JSON.stringify(openedArr));

Try above code after cleaning local storage. All should be good!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.