I'm trying to move elements from one array to another (columnsOut to columnsIn), but at the end not all values has been transferred (usually 2 out of 5 elements), so it seems something related to asynchronous state from react and I still do not how to cope with that. Can anyone give me directions?
columnsOut: [1, 2, 3, 4, 5]
columnsIn: []
function handleRemoveAllFilters(event) {
columnsOut.forEach((col) => (
setColumnsIn(columnsIn.concat(col))
));
setColumnsOut([]);
}
After running function:
columnsOut: []
columnsIn: [4, 5]
CodePudding user response:
The answer given by @Marian here has also been edited to match something similar to below:
function handleRemoveAllFilters(event) {
setColumnsIn(prev => ([...prev, ...columnsOut]));
// above will retain existing elements in columnsIn array
// below will discard
// setColumnsIn([...columnsOut]);
setColumnsOut([]);
};
CodePudding user response:
Change from setting the value for the setColumnsIn
to getting a callback that receives the previousState
as argument.
function handleRemoveAllFilters(event) {
columnsOut.forEach((col) => (
setColumnsIn((prevColumnsIn) => [...prevColumnsIn, col])
));
setColumnsOut([]);
}