I have a useState variable that holds log data and I'm displaying that data using .map(), at some particular moment, logs will be added, and I take the old variable and re affect the new value for it as the following :
const [logs, setLogs] = useState([])
const function1 = () => {
// some process here
setLogs(myValues)
}
const function2 = () => {
// some process
let myNewValues = logs
// some other process
setLogs(myNewValues)
}
.map() function displays the logs just fine after the first function, but when I update the logs with setLogs in the second function, .map() doesn't get the update, it displays the old values from function1.
How can I fix this in react ?
Thanks in adavance !
It appears to me that you may be mutating state, instead of passing a new state.
Instead of mutating the logs array and then calling setState with the same array reference, try spreading the new values into a new array object and then calling setState.
const function2 = () => {
let myNewValues = logs;
setLogs([...myNewValues]);
};
When setState is called, React looks at the object references, and sees that it received the same array reference, and then does not re-render. By passing a new array, React sees that state has changed, and will re-render accordingly.