Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React and Typescript, which types for Axios response?

I am trying to present a simple user list from an API which returns this:

[{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}] 

I do not understand fully how to handle Axios responses with types. The Typescript error is

Type '{} | { id: number; firstName: string; }' is not assignable to type 'IntrinsicAttributes & UserListProps & { children?: ReactNode; }'. Property 'items' is missing in type '{}' but required in type 'UserListProps'. 

from the <UserList /> element in the Users.tsx file below. Is my User interface wrong?

import React, {useEffect, useState, Fragment } from 'react'; import UserList from './UserList'; import axios, {AxiosResponse} from 'axios';  interface User {     id: number;     firstName: string; }  const Users: React.FC = (props) => {     const [users, setUserList] = useState<User>();      useEffect(() => {         // Use [] as second argument in useEffect for not rendering each time         axios.get('http://localhost:8080/admin/users')         .then((response: AxiosResponse) => {             console.log(response.data);             setUserList( response.data );         });     }, []);      return (         <Fragment>             <UserList {...users} />         </Fragment>      ); }; export default Users; 

Below is my UserList.tsx.

import React, {Fragment } from 'react';  interface UserListProps {     items: {id: number, firstName: string}[]; };  const UserList: React.FC<UserListProps> = (props) => {     return (         <Fragment>             <ul>             {props.items.map(user => (                 <li key={user.id}>                     <span>{user.firstName}</span>                     {/* not call delete function, just point to it                     // set this to null in bind() */}                 </li>             ))}             </ul>         </Fragment>     ); };  export default UserList; 
like image 557
G. Debailly Avatar asked Jun 05 '20 14:06

G. Debailly


People also ask

How do you type an Axios response in TypeScript?

Here is an example of an HTTP GET request using axios in TypeScript. Copied! import axios from 'axios'; type User = { id: number; email: string; first_name: string; }; type GetUsersResponse = { data: User[]; }; async function getUsers() { try { // 👇️ const data: GetUsersResponse const { data, status } = await axios.

How do you respond to react Axios?

First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request. You use axios. get(url) with a URL from an API endpoint to get a promise which returns a response object.

What is AxiosResponse?

The AxiosResponse is the response object returned as a Promise due to a REST API call such as GET or POST . TypeScript.

Does react use Axios?

It allows you to fetch data and make HTTP requests. This one is the common method to communicate with the database in React. In React there is another method to communicate with the backend server and that requires the installation of a popular library Axios.


1 Answers

There is generic get method defined in axios/index.d.ts

get<T = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R>; 

Example

interface User {     id: number;     firstName: string; }   axios.get<User[]>('http://localhost:8080/admin/users')         .then(response => {             console.log(response.data);             setUserList( response.data );         }); 

--Edit

I think you are passing list the wrong way to child component.

const [users, setUserList] = useState<User[]>([]); 
<UserList items={users} /> 
interface UserListProps {     items: User[]; }; 
const UserList: React.FC<UserListProps> = ({items}) => {     return (         <Fragment>             <ul>             {items.map(user => (                 <li key={user.id}>                     <span>{user.firstName}</span>                 </li>             ))}             </ul>         </Fragment>     ); }; 
like image 135
Józef Podlecki Avatar answered Oct 10 '22 19:10

Józef Podlecki