Home > Software design >  Types for arrow function with axios query inside
Types for arrow function with axios query inside

Time:03-25

my particular question is about typescript types. I've been searching web but found nothing for that example. What type can I define for a piece of code like this?

const useUserApi = () => {
const {
    token,
} = useUserState();

if (!token) return;

const getUserInfo = async () => {
    const res = await axios({
        url: Config.apiUrl   `getter/candidate`,
        method: 'get',
        headers: { Authorization: `Bearer ${token}` }
    });

    return res;
}

return {
    getUserInfo,
}

}

and I invoke it as

const {
    getUserInfo,
} = useUserApi();

useEffect(() => {
    getUserInfo()
    .then(function (response:any) {
        if (response.status === 200) {
            setUserData(prevState => ({ data: response.data, isLoading: false }))
        }
    })
    .catch((err: any) => {
        setError(err.response.data.message);
        if(err.response.data.error === 'invalid_token') toggleToken(null)
    });
}, [])

IDE says

const getUserInfo: any Property 'getUserInfo' does not exist on type '{ getUserInfo: () => Promise<AxiosResponse<any, any>>; changeUserInfo: (structure: Structure) => Promise<AxiosResponse<any, any>>; } | undefined'

Kind thanks for answer

CodePudding user response:

You can first write an interface about what you get from the api.

For example if you return array of Users

 interface User {
     id: number;
     firstName: string;
 }

Then;

 const getUserInfo = async (): Promise<User[]> => { //Array of Users in this case
    const res = await axios({
        url: Config.apiUrl   `getter/candidate`,
        method: 'get',
        headers: { Authorization: `Bearer ${token}` }
    });

    return res;
}

CodePudding user response:

Try this:

interface ExampleType {
    id: number;
    name: string;
}

const url = Config.apiUrl   `getter/candidate`
const config = {
    headers: { Authorization: `Bearer ${token}` }
};

const getUserInfo = async () => {
    const res = await axios.get<ExampleType>( url, config ); 

    return res.data; // The type of res.data is ExampleType
}

Tips:

No need to specify the return type of getUserInfo like this:

const getUserInfo = async (): Promise<ExampleType> => {}

Typescript will infer the type for you.

  • Related