lucaste
lucaste

Reputation: 570

how to set proper types in axios request for array of objects?

I'm trying to write a axios service for api requests and I have a problem with understanding this error:

Type 'AxiosResponse<User[]>' is missing the following properties from type 'User[]': length, pop, push, concat, and 26 more.ts(2740) const response: AxiosResponse<User[]>

My code looks like that:

import axios from 'axios';
import User from 'src/models/User';

const http = axios.create({
  baseURL: process.env.API,
  headers: { 'Content-Type': 'application/json' },
});

export async function getAllUsers(): Promise<User[]> {
  const response = await http.get<User[]>('users/');
  return response;
}

export async function getSingleUser(itemId: string): Promise<User> {
  const response = await http.get<User>(`/${itemId}`);
  return response;
}

For sure I'm not understading some basic typescript concept. Can u help me?

How this should be done if the response will be wrapped in 'data' poperty?

Upvotes: 0

Views: 1458

Answers (2)

Lin Du
Lin Du

Reputation: 102287

You should return the res.data for http.get() method, see Response Schema

import axios from 'axios';

interface User {}

const http = axios.create({
  baseURL: process.env.API,
  headers: { 'Content-Type': 'application/json' },
});

export async function getAllUsers(): Promise<User[]> {
  const response = await http.get<User[]>('users/').then(res => res.data)
  return response;
}

export async function getSingleUser(itemId: string): Promise<User> {
  const response = await http.get<User>(`/${itemId}`);
  return response;
}

TypeScript Playground

Upvotes: 0

Liad
Liad

Reputation: 844

What you are missing is the fact that the axios functions (such as get) return an AxiosInstance and not the actual object you expect. you should access the data property of the AxiosInstance to get the value you're expecting:

export async function getAllUsers(): Promise<User[]> {
  const response = await http.get<User[]>('users/');
  return response.data;
}

Upvotes: 1

Related Questions