Home > OS >  React with TypeScript - turn Axios Get method into Generic Axios Get Method
React with TypeScript - turn Axios Get method into Generic Axios Get Method

Time:06-03

I am trying to make my axios Get method into a generic method, so I can reuse it everywhere I need it.

I am having a bit of trouble on how to make it work. Let me show you some code

axios.get(`${urlUser}?userName=${getUserName()}`)
            .then((response: AxiosResponse<userProfile>) => {
                setProfile(response.data);
            })

This is the get method I am trying to convert to a generic method. the Url and the state function setProfile could be passed in as parameters, but the userProfile model needs to be an generic

export const Get = <T>(url: string, setState: any, Response: T) => {
    axios.get(url)
            .then((response: AxiosResponse<T[]>) => {
                setState(response.data);
        })
}

Here is the generic converted code. However, this could not work because in the AxiosResponse, I need to pass in some kind of model for the response.

I tried to add a generic Response parameter to the function, but it does not work to add the Response into the AxiosResponse<>

I dont think I am far off, any idea on how to fix this?

Many Thanks

CodePudding user response:

The solution

export const Get = <T,>(url: string, setState: any) => {
    axios.get(url)
            .then((response: AxiosResponse<T[]>) => {
                setState(response.data);
        })
}

the Get function, where its called

Get<userProfile>(`${urlUser}?userName=${getUserName()}`)
  • Related