How to let callback get the latest state? #2251
-
I'm trying to do the tutorial of React.js in yew, which is to write a tic-tac-toe game. But I came across a problem that callback seems don't get the latest state. Here is the repo: duskmoon314/yew-tictactoe In the app, there are three functional components:
In let winner = use_state_eq(|| SquareValue::None); And I use use_effect_with_deps(
move |(history, step, winner)| {
info!("use_effect winner {:?}", winner.clone());
let current = history.clone()[*step.clone()];
winner.clone().set(calculate_winner(current));
|| ()
},
(history.clone(), step.clone(), winner.clone()),
); Then I define these callbacks and pass them as props to children ( let handle_click = {
let history = history.clone();
let step = step.clone();
let winner = winner.clone();
info!("handle_click step {:?} winner {:?}", step, winner);
Callback::from(move |i: usize| {
let mut new_history = (*history).clone();
new_history.truncate(*step + 1);
let mut current = new_history[*step];
info!("handle_click callback step {:?} winner {:?}", step, winner);
if *winner != SquareValue::None || current[i] != SquareValue::None {
return;
}
current[i] = if *step % 2 == 0 {
SquareValue::X
} else {
SquareValue::O
};
new_history.append(&mut Vec::from([current]));
history.set(new_history);
step.set(*step + 1);
})
};
let undo = {
let step = step.clone();
let winner = winner.clone();
Callback::from(move |_| {
if *step > 0 {
step.set(*step - 1);
winner.set(SquareValue::None);
}
})
}; The problem is once the game is finished (one player wins the game), the This is my first time trying to write a yew app, and I don't know whether my way to form and pass callbacks to children components is correct. (I just learn this way from the |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I dont have time to fully look into you problem, but my guess is that your |
Beta Was this translation helpful? Give feedback.
-
Also possible solution is to group your game state into one |
Beta Was this translation helpful? Give feedback.
-
Thanks @voidpumpkin I figure out that I incorrectly implement PartialEq for callbacks that are passed as properties. So components are not rendered when callbacks are changed. |
Beta Was this translation helpful? Give feedback.
Thanks @voidpumpkin
I figure out that I incorrectly implement PartialEq for callbacks that are passed as properties. So components are not rendered when callbacks are changed.