1 year ago

#153938

test-img

princemuel

how can i type this axios request function properly and make it reusable using typescript

The purpose of the code below is to be resuable across projects maybe with slight modifications

  • The OnSuccess function handles the AxiosResponse
  • The OnError function handles the AxiosError

How can I define types for the data I'm getting from an api and use it to type the AxiosResponse in OnSuccess function and maybe other improvements like e.g the bearer token etc. Forgive me! I'm just an newbie

Here is the code below

import axios from 'axios';

const client = axios.create({
  baseURL: 'http://localhost:5500/',
});

export const request = ({ ...options }) => {
  client.defaults.headers.common.Authorization = `Bearer Token`;
  const onSuccess = (response) => response;
  const onError = (error) => {
    // optionally catch errors and add additional logging here
    // maybe redirect to login page to auth error
    return error;
  };

  return client(options).then(onSuccess).catch(onError);
};

export default client;

Calling Functions

const fetchSuperHeroes = () => {
  // return client.get('superheroes');
  return client({ url: '/superheroes' });
};

// OR
const addSuperHero = (hero) => {
  // return client.post('superheroes', hero);
  return client({ url: '/superheroes', method: 'post', data: hero });
};
// OR

const fetchSuperHero = ({ queryKey }) => {
  const heroId = queryKey[1];
  return client.get(`superheroes/${heroId}`);
};

Usage

  const { data, error } = useQuery('super-heroes', fetchSuperHeroes);

PS Ignore the querykey param in the last example usage function: it's just react-query syntax

typescript

axios

typescript-generics

code-reuse

0 Answers

Your Answer

Accepted video resources