I was trying to build a Tic Tac Toe game as a part of FFC challenge.
But I’m stucked at some points coz of the setState.
This function listen for a click event by the user and set the cell values according to the click and call another function after 1 second to make the bot play.
the botChoice function will generate a random index and check whether the cell is already filled or not.but the problem is the values array inside this function is before the update on the clickHandler function .(since setState is async).so it overwriting the existing cell values.(means if I (X) click on first cell and the bot also pick first cell then that cell will be ovewritten by “O”)
There have been a lot of these conversations of late. This is a great place to consider useEffect, as the check-for-win logic and the computer-turn logic are not directly related to the player-turn.
But, when the values changes, you can easily trigger a useEffect, check if isBotTurn, and handle any logic you need for that - and that would only trigger after the asynchronous setValues has happened.
It’s late, I’ll try to take a closer look tomorrow, but I’m a little confused.
I don’t understand this:
but the problem is the values array inside this function is before the update on the clickHandler function .(since setState is async)
It seems to work fine to me.
so it overwriting the existing cell values.
I’m not seeing this. I’ve played 20 games and I haven’t seen it once. The do while loop prevents this, right? Alternatively, you could have just selected randomly from the emptyCells return value, right?
If you’re worried about a race condition, couldn’t you put setIsBotTurn(false); after the other? Or could you use values as your dependency since you are creating a new reference when you set it? (I think.)
I don’t know, I’m tired, I’ll put a bookmark on this and look in the morning.