My question is, what should I modify on the interface so the number before the object (0, 1, ...) is generated automatically when the user click Add?
export interface IRoute {
amount?: string;
id?: number;
location?: string
}
export const initialRoute: IRoute = {
amount: '',
id: 0,
location: ''
}
const [route, setRoute] = useState<IRoute[]>([initialRoute]);
const nextId = route[route.length - 1].id 1;
const onAdd = () =>{[...prevState, {amount: '54', id: nextId, 'text'}]}
When the user clicks onAdd the response should look like this:
expected Behaviour:
route: [
{0:{amount: '45', id: nextId , location: 'Test'}},
{1:{amount: '35', id: nextId , location: 'Test'}}
]
actual Behaviour
route: [
{amount: '45', id: nextId , location: 'Test'},
{amount: '35', id: nextId , location: 'Test'}
]
CodePudding user response:
I see a couple of issues here.
- The code for
onAdd
doesn't do anything, and shouldn't compile becauseprevState
is undefined. The function states, but does'nt do anything with, the new array. I would expect it to be something likeconst onAdd = () => setRoute([...route, <newObj>]);
orconst onAdd = () => setRoute((prevState) => [...prevState, <newObj>]);
- You're not telling it to create the object the way you want it set. You would need something like
setRoute([...prevState, { [nextId]: <newObj> })
. - If you want
0
and1
to be the indexes of the array, you don't need to make them object keys, you can access them by index in the array you have by doingroute[index]
.