0

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);
   }
  }
Shivam
  • 19
  • 4
  • 1
    You can't use effects to update the state instantly, what you can do is use an effect to wait until the state has changed to show your console logs. Is that what you are trying to do? – DBS Oct 04 '21 at 15:13
  • @DBS how much time does it requires to show state change? I am trying to use this code in an interactive game, so need to perform operations on updated states too – Shivam Oct 04 '21 at 15:16
  • are you need to show the scores in the console? – nima Oct 04 '21 at 15:18
  • @pilchard I checked the post earlier. but since useEffect is showing error when using inside function (showSymbol) and need to change state whenever this function is called and logic executed. – Shivam Oct 04 '21 at 15:22
  • @novonimo yes I need to show player1 and player2 arrays in console as given in code. later, i'll remove console logs and perform operation on arrays. – Shivam Oct 04 '21 at 15:25
  • Your question was closed before I can post my answer to it. if it's not a duplication please edit your post and explain it. clarification will help you to open it again. – nima Oct 04 '21 at 15:29
  • @novonimo I was confused with using useEffect inside another function. but, looks like it's not needed as shown in the answer. Anyways, thanks for checking my question. – Shivam Oct 04 '21 at 15:39

1 Answers1

1

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.

tomleb
  • 2,409
  • 2
  • 9
  • 24