1

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
  },
]
1
  • Please, always show the actual error you're getting. Also, the array of objects that you're showing is looking suspicious. Unless the values of uuids are variables, you have to use quotes around them. Commented Oct 19, 2021 at 6:30

2 Answers 2

1

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}[]>([]);
Sign up to request clarification or add additional context in comments.

Comments

0
// 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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.