0

I am using react with typescript I am trying to fetch the data from the API using Axios. I created a state of an array of objects and tried to set the data from the response in Axios then:

const [users, setUsers] = useState<Users[]>([]);

type Users = {
    userId: number,
    name: string,
}

useEffect(() => {

const response = async () => {
        await axios.get(
          "https://localhost:5000/users",{
            headers: { "Content-Type": "application/json" },
          }
        );
      }

 response().then((res) => {
        setUsers({userId: res.userId, name: res.name})
      })


},[])

I am getting on setUsers saying: Argument of type '{ userId: any; }' is not assignable to parameter of type 'SetStateAction<Users[]>'. Object literal may only specify known properties, and 'userId' does not exist in type 'SetStateAction<Users[]>

2
  • Does this answer your question? How to add to state array in React Commented May 23, 2022 at 20:06
  • this question not related with typescript. Commented May 23, 2022 at 20:19

1 Answer 1

1

You need to append it to the last state:

response().then((res) => {
    setUsers((prevUsers) => prevUsers.concat(res));
    // setUsers((prevUsers) => [...prevUsers, res]); // another way
});

TypeScript is complaining because you are giving users a single Users object and not an array.

Sign up to request clarification or add additional context in comments.

1 Comment

still complaining: Type 'void' is not assignable to type 'Users'

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.