1

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 !

EL-Mehdi Loukach
  • 732
  • 2
  • 9
  • 28
  • Is it possible that you are mutating state instead of calling setState with a new array? In function2, try calling `setLogs([...myNewValues])`, this creates a new array from the myNewValues array, and then sets state. – Benjamin Mar 12 '22 at 00:01

1 Answers1

3

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.

Benjamin
  • 3,428
  • 1
  • 15
  • 25