How do I create and retrieve data from localStorage in this code?

110 Views Asked by At

I'm curious about the saving and retrieving from localStorage in Wordle and how is it implemented in React.

I'm building a Wordle clone as a project but I'm having a roadblock at this point. Most of the resources I found wouldn't go into how it works. If anyone ever has success with this thing, please help me out. Thanks a lot :)


In my case, I have a words.json file containing all the words.

  1. I want to set a timer so that after 10 minutes, the random correct word will change.
  2. All the guessed keys, guessed words, the counting timer, and the current correct word are saved in the localStorage so.
  3. When the correct word is changed, all data in the localStorage above are being reset to the fresh stage. (Yes, also clear out the tiles)

Problems:

  1. Up to this point, my code can fetch a new word every 10 minutes but I don't know how to save all of the data to the localStorage and reset them after 10mins.
  2. I set correctWord as an empty string for the initial state, if I type "" into the board, the game will break because it matches the winning condition. (currentWord === correctWord)
  3. The timer skips the number 0 and then restart the count down process again.
  4. I tried to save the timeLeft until the correct word is changed into the localStorage but it would just stay at 0 and not doing anything. If i refresh the page, the timer would just start from the start again, not from the point it should be left.
  5. I'm not applying the right code to save in the localStorage because I copied some of it. Please feel free to let me know what can I change to fit my code.

All code is embed in this codesandbox below

View Wordle

1

There are 1 best solutions below

0
On

You can set undefined as the initial state of the correctWord. Now, where-ever correctWord is being used , check if its undefined. If not, continue with the processing. You can use the ? operator for this usecase.

  const [correctWord, setCorrectWord] = useState(); 
  const correct = correctWord?.toUpperCase()[letterPosition] === letter

Also, the timer is not skipping 0, you are not seeing it printed in the logs due to the async nature of setState (Read more). This is the same reason, why you are seeing, 60 being logged twice in the console at the beginning.

To deal with this, use can set the newCounter value in a variable first, const newCount = counter-1, and then do setCounter(newCount), this prevents us from using the old value of a state,accidentally.

Also, I am able to set things in the localStorage,without any issue, for ex. localStorage.setItem("timeLeft", counter);

Hope this helps!