Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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[]>([]);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?
Thx.

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading