Local storage not working | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Local storage not working

I am trying to make a dice game which stores the lowest number of dice rolls and shortest time taken to finish the game and display in the bestTime and bestRolls state The value in the localStorage keeping changing back to 0 after re-rendering or refreshing Here’s the link to the code https://github.com/Mkhaleddd/tenzies-game

17th Jan 2023, 11:53 PM
Mariam Khaled
3 Answers
0
This logic make problem with first load: if (!bestRolls || rolls < bestRolls ) { console.log(rolls) setBestRolls(rolls) } So you have bestRolls on localStorage for example 5, and rolls is by default 0: if (!5 || 0 < 5) { setBestRolls(0) } !5 => !true => false false || 0 < 5 => false || true => true If run and setBestRolls to rolls what is 0, same happen for setBestTime. You should check what value is greater and set this value not always rolls As I said in previous comment we first set State(to localStorage value in your case), then component is mounted , then code from useEffect (life cycle method componentDidMount in your case) run and reset this to 0
19th Jan 2023, 10:33 PM
PanicS
PanicS - avatar
+ 1
Your setRecord function is called in useEffect(line 68) If you comment lines 77 and 81 you would see that localStorage work. You are changing values when "die" change what happen when user reload page so it reset. It reset because rolls and time what you place is 0 this info is not from localStorage, from localStorage you use bestRolls and bestTime, try to change console to log this values and you will see right value not 0. If you set this values except rolls or time it will work on reload but not on change. You need better logic for this function or make other function what just set default value. Ans another one for changing. In that way you would have more control. Note: we first set states, render page, then do componentDidMount(from use effect) and re-render page if needed.
19th Jan 2023, 1:12 PM
PanicS
PanicS - avatar
0
How can i exactly make a better function?
19th Jan 2023, 1:45 PM
Mariam Khaled