I recently added asynchronous code (Sockets) to a project and every time the state is called the original state value is passed. So far I've tried passing a callback to setState, and although that seemed to help, I ran into another issue the state no longer updated, i.e. the child component stopped re-rendering.
Below is the code which is most relevant. If you want another piece of code, don't hesitate to ask.
This code is called to update the state, which is a series of nested dictionaries, one named card contains an array of objects. The code updates the card we are calling it from, calls a function which returns a modified copy of the object and then passed that to a callback. Previously this was done by passing a copy of the original state, but that has the same issue.
const updateItem = useCallback(
(id, field, additionalData, value) => {
const { card, index } = findCard(id);
console.log("Updating item " + id);
const updatedCard = updateObject(card, additionalData, field, value);
setData((prevState) => {
const newState = {...prevState};
newState["HIT"]["data"][index] = updatedCard;
return newState;
});
},
[data]
);
The update function is called from an input in a child component. The state updates, but next time it is called the userInput value is "".
<input
type="text"
id="message"
autoComplete="on"
placeholder="Type a message"
value={props.Item['userInput']}
onChange={e => {props.updateItem(props.Item["id"],
"userInput",
{},
e.target.value);
}
}
/>
Any help would be greatly appreciated!