I've writing bellow example. his aim is to add asynchronously entries in an array contained in a React state.
My problem is my callback errase previous values rather than add them...
My runnable exemple is available here: https://codesandbox.io/s/nostalgic-kirch-7rtup?fontsize=14&hidenavigation=1&theme=dark
how to optain expected result?
thanks
You are overwriting each enqueued state update since all the state updates are enqueued within the same render cycle. You are also mutating state with the array::push.
const callback = (newValue) => {
const newState = clone(state);
newState.myValue.push(newValue); // <-- state mutation!
setState(newState);
};
const exe = () => {
setTimeout(() => callback("b"), 1000); // <-- all updates from current state!
setTimeout(() => callback("c"), 2000);
setTimeout(() => callback("d"), 3000);
};
Use functional state updates to correctly update from previous state.
const callback = (newValue) => {
setState(state => ({
...state, // <-- copy existing state
myValue: [...state.myValue, newValue], // <-- copy array and append new value
}));
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.