Home > Mobile >  React Native - Type Script - Object should be changeble to a number when user clicks add
React Native - Type Script - Object should be changeble to a number when user clicks add

Time:07-13

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.

  1. The code for onAdd doesn't do anything, and shouldn't compile because prevState is undefined. The function states, but does'nt do anything with, the new array. I would expect it to be something like const onAdd = () => setRoute([...route, <newObj>]); or const onAdd = () => setRoute((prevState) => [...prevState, <newObj>]);
  2. You're not telling it to create the object the way you want it set. You would need something like setRoute([...prevState, { [nextId]: <newObj> }).
  3. If you want 0 and 1 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 doing route[index].
  • Related