I am working with a legacy database, where is there no unique index number for each row. Still, I want to have the ability to update items a row. I created a child component, which has a form, to update a row. I am able to identify the index number of the row. And then I move the updated values, and the index number, up to the parent. I'm trying to update the state at the parent level.
My problem is that I am unable to update the state at the parent level.
Here are portions of my code:
//Gifts is a js file with json
import { Gifts } from "./Gifts";
const Main = (props) => {
const [gifts, setGifts] = useState(Gifts);
const handleEditSubmit = (values) => {
console.log(values);
setGifts(gifts =>
{const list = gifts.map((gift, index) => {
if (index === values.index) {
delete values.index;
return values;
} else {
return gift;
}
});
console.log(list);
return (
{list}
)
});
console.log(gifts);
};
return(
<div>
<div>
<GiftDisplay gifts={gifts}
onFormSubmit={handleGiftCreate}
onEditSubmit={handleEditSubmit}
/>
</div>
</div>
);
};
I have another function, called handleGiftCreate
, which works just fine.
When I check the output of console.log(list)
, the output is correct. The list has the updated row. But when I check console.log(gifts)
, I see that the state has not updated.
Initial state of the fourth row is
{
"AutoId": 4263,
"ID": 0,
"Year": 2021,
"Date": "2020-12-31T00:00:00.000Z",
"Transaction": "Gift",
"AmountOld": 0,
"Deposit": "PayPal",
"Amount": 20
}
Notice that the initial state Amount is 20.
The values - input to the handleEditSubmit - is
{index: 4, AutoId: 2810, ID: 0, Year: 2021, Date: '2020-12-31T00:00:00.000Z', …}
Amount: "2588"
AutoId: 2810
Date: "2020-12-31T00:00:00.000Z"
Deposit: "PayPal"
ID: 0
Transaction: "Gift"
Year: 2021
Notice that the Amount is updated to 2588.
Fourth item of console.log(list)
is
Amount: "2588"
AutoId: 2810
Date: "2020-12-31T00:00:00.000Z"
Deposit: "PayPal"
ID: 0
Transaction: "Gift"
Year: 2021
Note that the amount updated properly in list.
The result of console.log(gifts)
, however, is
Amount: 25
AmountOld: 0
AutoId: 2810
Date: "2020-12-31T00:00:00.000Z"
Deposit: "PayPal"
ID: 0
Transaction: "Gift"
Year: 2021
The state did not update! Please help!