Search code examples
reactjsreact-hookslocal-storagejsxuse-effect

I cant get the localStoarge data, i'm using useEffect Hook


Every Time i try to refresh the page it returns to 0. I'm taking the bestScore from turns when the match is equal to 6, so basically everytime the matched cards hit 6 it will take the bestScore from the turns and save the bestScore to localStoarge and it works but when i try to refresh its gone

 function App() {
      const [cards, setCards] = useState([]);
      const [turns, setTurns] = useState(0);
      const [match, matchedCards] = useState(0);
        const [bestScore, setBestScore] = useState(
    localStorage.getItem("highestScoresss")
  );
  const [choiceOne, setChoiceOne] = useState(null); //Kullanici 1.karta basinca setChoiceOne o karti alacak ve guncelliyecek
  const [choiceTwo, setChoiceTwo] = useState(null); //Kullanici 2.karta basinca setChoiceTwo o karti alacak ve guncelliyecek
  const [disabled, setDisabled] = useState(false);
  useEffect(() => {
    if (match === 6) {
      const highScore = Math.min(turns, bestScore);
      setBestScore(highScore);
      setBestScore(turns);
    } else {
      console.log("false");
    }
  }, [turns]);
  useEffect(() => {
    localStorage.setItem("highestScoresss", JSON.stringify(bestScore));
  });

This Is the JSX

<div className="bilgi">
        <p>Sıra: {turns}</p>
        <p>Bulunan: {match}</p>
        <p>En iyi Skor: {bestScore}</p>
        <button onClick={shuffleCards}>Yeni Oyun</button>
      </div>
    </div>

Solution

  • The issue with your implementation is that you set state to 0 first, and then the useEffect hook runs and sets localStorage to the state value.

    If you are potentially initializing your state to a value stored in localStorage then I suggest using a lazy initialization function so the initial state value is set before the initial render and eliminates the need for the additional useEffect hook to set state from storage. This reads from localStorage and returns the parsed value, or 0 if the parsed result is null or undefined.

    const initializeState = () => {
      return JSON.parse(localStorage.getItem("highestScoresss")) ?? 0;
    };
    
    ...
    
    const [bestScore, setBestScore] = useState(initializeState());
    

    You will want to use a dependency array on the useEffect that is persisting the "highestScoresss" value in localStorage such that it only triggers when the bestScore state value updates and not on each and every render.

    useEffect(() => {
      localStorage.setItem("highestScoresss", JSON.stringify(bestScore));
    }, [bestScore]);