Type 'AxiosResponse<IUser, any>' is not an array type

I have a some small problem with typing axios response.
I have method that return user profile from API:

 static async getProfileById(id: string | undefined){
    const jwt = localStorage.getItem("jwt");

    const response = await axios.get<IUser>(`http://localhost:4000/api/feed/id?id=${id}`, {
        headers: {
            authorization: "Bearer " + jwt

    return response;

interface IUser:

export interface IPost{
    _id: string,
    title: string,
    body: string,
    viewed: number,
    likes: number,
    comments: number,
    author: string,
    image: string,
    __v: number,
    date: string,
    isLiked: boolean

I create const that I put user profiles:
const [subs, setSubs] = useState<IUser[]>([]);

And there I adding profiles to const subs:

for (let i =0; i < response.length; i++){
    const profileSub = await UserService.getProfileById(response[i]);

    console.log(typeof profileSub);

    setSubs([...subs, ...profileSub])

But I got error : ‘Type ‘AxiosResponse<IUser, any>’ is not an array type’.

What am I doing wrong?

>Solution :

subs is an array, of type IUser[], and profileSub is an object, of type IUser. You cannot spread an object into an array. If you want to add profileSub to the subs array, you would do:

setSubs([...subs, profileSub])

Simply add the profileSub into the new subs array without spreading it.

Note: if you want to return the user profile from getProfileById, you have to return response.data.

Leave a Reply