Basically what I have are two components, a parent and a child. Through a props I intend to update the state of the parent component. Inside child component I have a function called updateData() which is triggered by a button.
const updateData = props.setDataState;
const thisComponentData = props.dataToUs;
const handleUpdateData = () => {
const getIndex = data.findIndex((item) => item.id === thisComponentData.id);
data[getIndex].category.vehicles = 1
data[getIndex].category.vehicles = 2
return updateData(data)
};
The problem is that even I trigger this function, the state of the parent component doesn't change. My hypothesis is that this isn't identifying the state modification I'm doing.
EDIT
The parent component is basically a functional component in which I props the setDataState.
const [data, setData] = useState([]);
// An api inserts the setData data
<Parent
dataToUs={data}
setDataState={(value) => setData(value)}/>
CodePudding user response:
First you have two functions named the same: updateData
.
In your case if setDataState
is probably a function in parent component, then your function updateData
should look like this:
// This variable name should change
const setDataState = props.setDataState;
const thisComponentData = props.dataToUs;
const updateData = () => {
const updatedDataArray = data.map((item) => {
if (item.id === thisComponentData.id)
return {
...item,
category: {
...item.category,
vehicles: 2,
}
}
return item;
});
setDataState(updatedDataArray)
};
EDIT: Edited code so that it uses .map.