Home > front end >  How can useEffect be used in this case to update state instantly? Or any alternative approach [dupli
How can useEffect be used in this case to update state instantly? Or any alternative approach [dupli

Time:10-05

I'm looking for a way to show updated state "filledBoxes" when console.log requires in code. But the updated state is showing up one turn later.

I can't figure out how to use 'useEffect' in this case. It gives error when used inside "showSymbol" function. Please, let me know how to solve this situation.

function Playfield() {

  const [ turn, setTurn ] = useState(0);
  const [ filledBoxes, setFilledBoxes ] = useState({
    player1: [],
    player2: []
  });

  function showSymbol (event) {
     // console.log(event);

   if(event.target.innerHTML === "") {

      if(turn%2 === 0) {
        event.target.innerHTML = "X";
        setFilledBoxes(prevValue =>  ({
              ...prevValue,
             player1: [...prevValue.player1, event.target.id]
           })
         );
      } else {
        event.target.innerHTML = "O";
        setFilledBoxes(prevValue =>  ({
              ...prevValue,
             player2: [...prevValue.player2, event.target.id]
           })
         );
      }

     console.log(filledBoxes.player1);
     console.log(filledBoxes.player2);

     setTurn(turn   1);
   }
  }

CodePudding user response:

useEffect doesn't cause the state to update immediately.
It's simply a built-in hook that "listens" to changes in it's dependencies,
and performs a callback that you pass to it, once any of those dependencies has changes.
It is used in cases like these to perform a certain action/s once a change occurs.

So doing -

useEffect(() => {
   console.log(state);
}, [state])

Will show you the state once it finishes updating.
For more info.

  • Related