Reputation: 570
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
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;
}
Upvotes: 0
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