I have declared a react hook which will contain an array of object as follows:
const [rowDataTracker, setRowDataTracker] = useState([]);
Now I need to update the hook to basically create a payload as the following:
[
{id: 100, payload: {field1: "value", field2: "value"}},
{id: 105, payload: {field1: "value", field3: "value"}},
{id: 109, payload: {field4: "value"}}
]
I need to check the following condition Before updating the hook:
- Need to first check if the id exists in the array or not
- if the id exists, then need to update/add the filed to the payload object
- if the id does not exist, add a new object to the array with id and the field
const ifItemExist = (arr, item) => {
return arr.findIndex((e) => e.id === item);
};
function storeEdit(rowId, field, newValue) {
let itemIndex = ifItemExist(rowDataTracker, rowId);
let newArr = [...rowDataTracker];
if (itemIndex > -1) {
newArr[itemIndex]["payload"][columnId] = newValue;
} else {
const obj = {
itemNbr: rowId,
payload: {
[field]: newValue
}
};
newArr.push(obj);
}
setRowDataTracker(newArr);
}
I am not sure if this is the correct way to update a hook. Any review and suggestion will be appreciated.