I'm still getting a hang of hooks in React. I am making a tic tac toe game to understand the concept of the useState hook. Everything works fine but I need to make an extra move to find the winner. This is because I'm calling a function on every user move, and that function is unable to get the updated state, it always has one step older state of the game.
Here is the link to the CodeSandbox. Here is how the flow works:
First Render: Game function calls -> Board function -> Board uses a custom hook, useBoardState -> useBoardState initializes an empty array of size 9 in the state, and returns array and a function updateSquares to update the state(+ there is some other stuff to render the UI but unrelated to the issue).
When the user clicks on an empty box: selectSquare function gets called -> selectSquare calls updateSquares to update the state(+ some other stuff to make the game usable.)
Observe that the console in the selectSquare function has the stale state even when the updateSquares was executed. I was expecting that the state would be updated function was called.
As requested in the comments, I'm adding the relevant part of the code here:
function useBoardState() {
const [squares, setSquares] = useState(() => Array(9).fill(null));
function updateSquares(index, mark) {
setSquares((prevSquares) => {
const newSquares = [...prevSquares];
newSquares[index] = mark;
return newSquares;
});
}
return [squares, updateSquares];
}
I think it has something to do with this custom hook, I think the updateSquares state dispatcher updates the state when the render is complete.
not sure what am I missing here.
the setter returned from useState as well as the class based component equivelant setState are not called synchronously. That is why if you do something like
const updateSomething = () => {
setFoo(1)
setBar(2)
setFooBar(3)
console.log('hey')
}
React will log hey before it starts setting the state, furthermore it will actually batch setFoo, setBar and setFooBar together, so it does a single rerender with all the above state updates.
Related
Logic:
I have a dialog for converting units. It has two stages of choice for the user: units to convert from and units to convert to. I keep this stage as a state, dialogStage, for maintainability as I'm likely going to need to reference what stage the dialog is in for more features in the future. Right now it's being used to determine what action to take based on what unit is clicked.
I also have a state, dialogUnits, that causes the component to rerender when it's updated. It's an array of JSX elements and it's updated via either foundUnitsArray or convertToUnitsArray, depending on what stage the dialog is at. Currently both states, dialogStage and dialogUnits, are updated at the same moment the problem occurs.
Problem:
When choosing the convertTo units, displayConversionTo() was still being called, as though dialogStage was still set to 'initial' rather than 'concertTo'. Some debugging led to confusion as to why the if (dialogStage == 'initial') was true when I'd set the state to 'convertTo'.
I believe that my problem was that the dialogStage state wasn't updated in time when handleUnitClick() was called as it's asynchronous. So I set up a new useEffect that's only called when dialogStage is updated.
The problem now is that the dialog shows no 'convertTo' units after the initial selection. I believe it's now because dialogUnits hasn't updated in time? I've swapped my original problem from one state not being ready to another state not being ready.
Question
How do I wait until both states are updated before continuing to call a function here (e.g. handleUnitClick()?).
Or have I mistaken what the problem is?
I'm new to react and, so far, I'm only familiar with the practice of state updates automatically rerendering a component when ready, unless overridden. Updating dialogUnits was displaying new units in the dialog until I tried to update it only when dialogStage was ready. It feels like an either/or situation right now (in terms of waiting for states to be updated) and it's quite possible I've overlooked something more obvious, as it doesn't seem to fit to be listening for state updates when so much of ReactJs is built around that already being catered for with rerenders, etc.
Component code:
function DialogConvert(props) {
const units = props.pageUnits;
const [dialogUnits, setDialogUnits] = useState([]);
const [dialogStage, setDialogStage] = useState('initial');
let foundUnitsArray = [];
let convertToUnitsArray = [];
units.unitsFound.forEach(element => {
foundUnitsArray.push(<DialogGroupChoice homogName={element} pcbOnClick={handleUnitClick} />);
});
useEffect(() => {
setDialogUnits(foundUnitsArray);
}, []);
useEffect(() => {
if (dialogStage == "convertTo") {
setDialogUnits(convertToUnitsArray);
}
}, [dialogStage]);
function handleClickClose(event) {
setDialogStage('initial');
props.callbackFunction("none");
}
function handleUnitClick(homogName) {
if (dialogStage == "initial") {
// getConversionChoices is an external function that returns an array. This returns fine and as expected
const choices = getConversionChoices(homogName);
displayConversionTo(choices);
} else if (dialogStage == "convertTo") {
// Can't get this far
// Will call a function not displayed here once it works
}
}
function displayConversionTo(choices) {
let canConvertTo = choices[0]["canconvertto"];
if (canConvertTo.length > 0) {
canConvertTo.forEach(element => {
convertToUnitsArray.push(<DialogGroupChoice homogName={element} pcbOnClick={handleUnitClick} />);
});
setDialogStage('convertTo');
}
}
return (
<React.Fragment>
<div className="dialog dialog__convertunits" style={divStyle}>
<h2 className="dialogheader">Convert Which unit?</h2>
<div className='js-dialogspace-convertunits'>
<ul className="list list__convertunits">
{dialogUnits}
</ul>
</div>
<button className='button button__under js-close-dialog' onClick={handleClickClose}>Close</button>
</div>
</React.Fragment>
)
}
So, there are some issues with your implementations:
Using non-state variables to update the state in your useEffect:
Explanation:
In displayConversionTo when you run the loop to push elements in convertToUnitsArray, and then set the state dialogStage to convertTo, you should be facing the issue that the updated values are not being rendered, as the change in state triggers a re-render and the convertToUnitsArray is reset to an empty array because of the line:
let convertToUnitsArray = [];
thus when your useEffect runs that is supposed to update the
dialogUnits to convertToUnitsArray, it should actually set the dialogueUnits to an empty array, thus in any case the updated units should not be visible on click of the initial units list.
useEffect(() => {
if (dialogStage == "convertTo") {
// as your convertToUnitsArray is an empty array
// your dialogue units should be set to an empty array.
setDialogUnits(convertToUnitsArray)
}
}, [dalogStage]);
You are trying to store an array of react components in the state which is not advisable:
http://web.archive.org/web/20150419023006/http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state
Also, refer https://stackoverflow.com/a/53976730/10844020
Solution: What you can do is try to save your data in a state, and then render the components using that state,
I have created a code sandbox example how this should look for your application.
I have also made some changes for this example to work correctly.
In your code , since you are passing units as props from parent, can you also pass the foundUnitsArray calculated from parent itself.
setDialogUnits(props.foundUnitsArray);
and remove the below operation,
units.unitsFound.forEach(element => {
foundUnitsArray.push(<DialogGroupChoice homogName={element} pcbOnClick={handleUnitClick} />);
});
I am writing an application that basically is a game. The information about the game is stored in a context provider that wraps the entire application. I have written prototype methods for the game object and call them in the react app but the changes do not appear on the page.
const onDeckEl = useRef(null)
useEffect(() => {
let onDeck = round.getOnDeck()
onDeckEl.current = onDeck
console.log(onDeckEl)
}, [round])
I can see in the dev tools that the values of the arrays in the round object are changing when I want but the console.log is never fired. Can someone explain why?
The most likely reason the console.log is not firing is because the round variable isn't changing. The code:
useEffect(() => {
console.log('Effect!');
}, [round])
wont fire unless the round variable changes.
I have a simple cart function that, when a user clicks to increase or decrease the quantity of an item in a shopping cart, calls a useState function to update the cart quantity in state.
const [cart, setCart] = useState([]);
const onUpdateItemQuantity = (cartItem, quantityChange) => {
const newCart = [...cart];
const shouldRemoveFromCart = quantityChange === -1 && cartItem.count === 1;
...
if (shouldRemoveFromCart) {
newCart.splice(cartIndex, 1);
} else {
...
}
setCart(newCart); //the useState function is called
}
so in jest, I have a function that tests when a user sets a cart item's quantity to zero, but it does not yet remove the item from the cart, I'm assuming because it has not yet received the results of setCart(newCart):
test('on decrement item from 1 to 0, remove from cart', () => {
const [cartItemToDecrement] = result.current.cartItems;
const productToDecrement = result.current.products.find(
p => p.id === cartItemToDecrement.id
);
act(() => {
result.current.decrementItem(cartItemToDecrement);
});
act(() => {
result.current.decrementItem(cartItemToDecrement);
});
...
expect(result.current.cartItems).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: cartItemToDecrement.id,
count: cartItemToDecrement.count - 2,
inventory: productToDecrement.inventory + 2
})
])
);
});
});
This test passes, because the cart now contains an item whose quantity has dropped to zero. But really it shouldn't, because from the splice operation in onUpdateItemQuantity our cartItems array should now not include the object at all. How do I verify in my jest test that this removal is happening (the react code works properly).
I do not really understand the relation between the test and your onUpdateItemQuantity very much because the context you provided is not sufficient to me.
But from your question, there are 2 clues which may help to save your time.
You may know setCart from useState is not synchronous, so that if you try to access cart from useState at the same frame, it shouldn't reflect the change even though you ensure setCart called. useEffect is a good solution. You can find the doc of useEffect [https://reactjs.org/docs/hooks-effect.html][1], any change should be reflected in useEffect, perhaps you can put your test there.
Add an extra variable myCart to store cart and a function setMyCart. Instead of calling setCart in your code, call setMyCart. setMyCart is like,
function setMyCart(newCart)
{
myCart = newCart;
setCart(myCart); // this is for triggering React re-render
}
then use myCart which can reflect the change immediately for testing.
The only purpose of the additional code in the 2nd point, is when we still rely on the re-render mechanism of React, we use our own Model myCart for our particular logic rather than cart state from React which is not only for View but also used for our logic on an inappropriate occasion.
Testing for state changes is a challenge, because it doesn't produce any specific output (except whatever impacts your render).
The key is to narrow the testing scope to your responsibilities, versus testing React. React is responsible for making sure that useState updates the state properly. Your responsibility is to make sure you are using the data properly and sending the correct data back. So instead of testing useState, test how your component responds to the state it is given, and make sure you are setting the correct state.
The answer to to mock useState. Give it an implementation that returns the initial value passed to it, with a mock function that lets you read what data is being saved.
More detailed answer here:
https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga
HTH!
If you need to test every state update using useState(), you can do so by implementing a useEffect function that listens specifically for that state change, in your case, cart:
useEffect(() => {
test(...)
), [cart]);
And so you can do the test inside the useEffect() function.
That will ensure that you have the correct value of cart and it will be called every time cart is updated.
It's totally unclear how onUpdateItemQuantity is called. And even what it does exactly. Never the less, you claim that toEqual(...[{...,count:cartItemToDecrement.count - 2,...}]...) passes. That probably means that onUpdateItemQuantity is called inside of decrementItem, inside of onUpdateItemQuantity there is something like newCart[cartIndex].count--, and if toEqual() passes, that means that setState() successfully updates the state, and after act() you have the actualized state. And if test's name is correct and initial value of cartItemToDecrement.count === 1 that should mean that cartItemToDecrement.count - 2 === -1 and you never go inside of if (shouldRemoveFromCart). So maybe the issue is not with the test, but with the code.
Lets say I have the following component using react hooks
const Component = (props) => {
[state1, setState1] = useState();
[state2, setState2] = useState();
useEffect(()=>{
// use state1 and state2 as param to fetch data
...
}, [state1, state2])
onSomethingChange = () => {
setState1(...);
setState2(...);
}
return (..);
}
When onSomethingChange triggers, I thought it would call the side effect function twice since I update 2 different state vars in the same dependency array. And I was going to refactor those 2 vars into 1 object but I thought I would test them as 2 separate vars first.
What I observed is the side effect function only gets executed once even when I update 2 different state vars in the same dependency array, this is what I wanted but I don't know why. Could someone please explain how it works under the bonnet?
That's because React sometimes may batch multiple state changes into one update for performance. React will batch state updates if they're triggered from within a React-based event, that's the reason why your side effect block is called only once. For more information, you may refer this thread: https://github.com/facebook/react/issues/14259
React batches state updates under the hood.
That simply means that calling
setState1(...);
setState2(...);
in the same synchronous (!) execution cycle (e.g. in the same function) will NOT trigger two component re-render cycles.
Instead, the component will only re-render once and both state updates will be applied simultaneously.
Not directly related, but also sometimes misunderstood, is when the new state value is available.
Consider this code:
console.log(name); // prints name state, e.g. 'Doe'
setName('John');
console.log(name); // ??? what gets printed? 'John'?
You could think that accessing the name state after setName('John');
should yield the new value (e.g. 'John') but this is NOT the case.
The new state value is only available in the next component render cycle (which gets scheduled by calling setName()).
Hi so here is the situation. I am building a tictactoe game with react and I have 3 components
1. GameParent
2. board
3. gameControls
I have a function inside GameParent component has two state properties called AI and Game which are objects. I pass these objects down as a prop to the board component. It also has a function called startGame()
startGame() {
let newAI = new AI(this.state.AIIdentity);
let newGame = new Game(newAI,this.state.AIIdentity);
this.state.AI.plays(this.state.Game);
this.state.Game.start();
this.setState({
start: true,
AI: newAI,
Game: newGame,
});
console.log("THIS!!!",this)
console.log("THIS!!!",this.state)
console.log("THIS!!!",this)
console.log("THIS!!!",this.state.Game);
}
When this.state.Game.start() is called there is a property called status inside the Game object that should be changed to "running"
I pass the startGame() function down to my gameControls component and I attach it to my start button onClick handler.
My board component handles the clicks on the squares of the board but it only registers clicks if the Game.status === "running" but I keep getting the object with a status === "beginning".
So when I added these 4 console.logs, when I print out only this, I see that the Game object's status is "beginning" however when I console.log this.state and this.state.Game, the status is set to "running"!
I am so confused why this is happening... I'm guess it's the way React update it's child but I haven't found an explanation from reading how render() and setState() works. Or maybe I'm not completely understanding how "this" is affect when I pass down functions and objects to child components.
If you guys want to see the full code, here is the link
http://codepen.io/comc49/pen/WRqBXr?editors=0110
You should not put function inside the state. State is for data only. I think that could be one source for unexpected behavior.
this.setState is an asynchronous function, that means that there is no guarantee that the state is set right after you call this.setState. That could explain the unexpected output from the console.logs