I have an array object inside a state and it will be updated onChange, I was able to update but only for a single property, my problem is if the property has a nested object like the example below, I can't update because I'm not sure on how to pass the field or the property of the selected. Any help will be appreciated.
import React, { useEffect, useState } from 'react';
const TestPage = () => {
const [state, setState] = useState([
{
test: 'test 1',
current: {
now: 'now 1',
prev: 'prev 1'
}
},
{
test: 'test 2',
current: {
now: 'now 2',
prev: 'prev 2'
}
}
]);
const handleChange = ({ prevState, index, params, value }) => {
const curState = [...prevState];
curState[index][params] = value;
setState(curState);
};
useEffect(() => {
console.log(state);
}, [state]);
return (
<div>
{state.map((item, i) => {
return (
<div key={i}>
<input
type="text"
value={item.test}
onChange={(e) =>
handleChange({ prevState: state, index: i, params: 'test', value: e.target.value })
}
/>
<input
type="text"
value={item.current.now}
onChange={(e) =>
handleChange({ prevState: state, index: i, params: 'now', value: e.target.value })
}
/>
</div>
);
})}
</div>
);
};
export default TestPage;
Edit:
What if the object has too many nested object like the array object below and I would want to update the others property
const [state, setState] = useState([
{
test: 'test 1',
current: {
now: 'now 1',
prev: 'prev 1',
others: {
other1: 'other 1',
other2: 'other 2'
}
}
},
{
test: 'test 2',
current: {
now: 'now 2',
prev: 'prev 2'
}
}
]);