I have a component class A which contains as state a data object containing an array of objects, each of these objects have an attribute, and I need to know with the useEffect which index actually changed:
Component A
import React, { useEffect } from 'react';
export default class ComponentA extends React.Component {
constructor(props) {
super(props);
this.state = {
data: Array.from(Array(3).keys()).map(i => {
return {
id: i,
data: props.initialData
};
});
};
}
// at this point I have my state and want to monitor changes
// but how to monitor useEffect and tell which index element
// within state.data changed?
};
>Solution :
First, you need to convert your component to a functional component to use a useEffect hook. I would do something like this:
import React, {
useEffect,
useState
} from 'react';
const ComponentA = ({initialData}) => {
const [state, setState] = useState(Array.from(Array(3).keys()).map(i => {
return {
id: i,
data: initialData
};
});
return // some jsx
)};
As far as your question, I would update some state variable that tracks the id of the object being changed when you update state. For example, when you call setState and change one of the objects in the array, also set some other piece of state called changedId with the id of the object you changed. Once the useEffect is called, the state has already been changed and it is too late to check what the change was.
Here is how I would do that generally:
import React, {
useEffect,
useState
} from 'react';
const ComponentA = ({initialData}) => {
const [state, setState] = useState(Array.from(Array(3).keys()).map(i => {
return {
id: i,
data: initialData
};
});)
const [changedId, setChangedId] = useState(null);
// Somewhere else in the app you change the state...
// Update the changedId at that time
const someStateUpdatingFunction = () => {
setState(//newValue)
setChangedId(//idForChangedArrayItem)
}
// Then once the state updates, the effect is called
useEffect(() => {
//some effect here
}, [state])
return // some jsx
};
Hope that is helpful. Just remember, the useEffect hook does not track state changes over time. It is simply some functionality that is triggered when the state changes.