I am having trouble understanding the following behaviour of React
interface DataProps {
animal: string,
age: number,
origin: {
country: string,
alive: boolean
}
}
const Foo = () => {
const [data, setData] = useState<DataProps[]>([])
const _updateOriginProp = <K extends keyof DataProps["origin"]>(
index: number,
data: Array<DataProps>,
key: K,
payload: boolean,
): Array<DataProps> => data.map((animal, idx) => {
if (idx === index) return {
...animal,
origin: {
...animal.origin
[key]: payload,
},
};
return animal;
});
const _setData = () => {
let updatedData = cloneDeep(data)
updatedData = _updateOriginProp(index, updatedData, 'alive' false)
console.log('updatedData')
console.log(updatedLegs)
setData(updatedData)
}
console.log("data")
console.log(data)
return null
}
Whenever the _setData()
function is triggered, it loggs
updatedData
[{…}, {…}]
With the updated origin.alive
as I would expect it. Afer the setData()
a re-render is triggered, and the the console.log("data")
and console.log(data)
is logged, only once (indicating there are no other re-renders triggered). However, the prop origin.alive
is not updated as set in _setData()
and I do not understand why. Logging updatedData
in setData()
, I can verify that the prop is changed. Why is it not reflected in the data state
when a re-render is triggered?