Home > Mobile >  I want to add an object to the react array
I want to add an object to the react array

Time:10-19

I want to add an object to the state array.
I want to add an object {user.uuid,user.id} to the state array using the spread syntax, I want to add an object {user.uuid,user.id} to the state array. But I get an error and can't add any value to the state. If anyone knows how to solve this problem, please let me know.

  const [id, setId] = React.useState<[{uuid: number; id: number}]>([]);

  useEffect(() => {
    if (id === null) {
     users.map((user) => setId([...id, {user.uuid, user.id}]));
    }
  }, [users]);

I would like to create such an array.

[
  { uuid:sadsa
    id:1
  },
  { uuid:dadsad
    id:2
  },
  { uuid:jihji
    id:3
  },
  { uuid:mokok
    id:4
  },
]

CodePudding user response:

My understanding from your code is that your state is an array, which means that the type you want to use is {uuid: number; id: number}[]. Thus, the useState statement should be:

const [id, setId] = React.useState<{uuid: number; id: number}[]>([]);

CodePudding user response:

// define Item type
type Item = {
    uuid: number, id: number
}

// define type as Item array
const [id, setId] = React.useState<Item[] | []>([]);

const user: Item = { uuid: 1, id: 123 };

// setId accepts array of Item, So
setId([...id, user]);
  • Related