DEV Community

Vicky Vasilopoulou
Vicky Vasilopoulou

Posted on

React Query Tanstack, axios and customised hooks

Hello guys!😀

Thank you for reading my article!

This one is short but I hope you find some value to it and give you some ideas to be more creative with your code ❤️

The concept is to create the connection between the frontend app + graphql + server for transferring data back and forth. I am gonna share an example doing a GET request.

Firstly we need to set up our http-client


const instance = axios.create({
  baseURL: config.ApiBaseUrl,
  headers: {
    'Content-type': 'application/json',
  },
})

export default setupYourInterceptors(instance)
Enter fullscreen mode Exit fullscreen mode

In the code below your ApiBaseUrl could be your actual API. In the case below I am storing it in this format.


const { YOUR_API_BASE_URL } = = import.meta.env

const config: Configuration = {
  ApiBaseUrl: 'YOUR_API_BASE_URL' || 'default'
}

Enter fullscreen mode Exit fullscreen mode

Axios interceptors allow you to run your code or modify the request and/or response before the request is sent or after the response is received.

  • onRequest is a function that will be called before each request is sent. It can modify the request configuration.

  • onResponseError is a function that will be called if the response results in an error. This allows for centralized error handling.


function setupYourInterceptors(axiosInstance: AxiosInstance): AxiosInstance {
  axiosInstance.interceptors.request.use(onRequest, undefined)

  axiosInstance.interceptors.response.use(undefined, onResponseError)

  return axiosInstance
}

Enter fullscreen mode Exit fullscreen mode

Now lets create a book service. Lets say we are searching for books.


const endpoint: string = '/books'

const getBooks = async (): Promise<BooksResponse[]> => {
  const { data: response } = await httpClient.get<BooksResponse[]>(`${endpoint}`)
  if (response) {
    return response.items
  }
  throw new Error('Data is undefined')
}

export default getBooks

Enter fullscreen mode Exit fullscreen mode

Lastly our customisable hook for fetching books.

function useGetBooks() {
  return useQuery({
    queryKey: ['books'],
    queryFn: () => getBooks(),
  })
}

Enter fullscreen mode Exit fullscreen mode

Thank you for reading it 😀

Top comments (1)

Collapse
 
tytom2003 profile image
tom

how can use axiosInstance in getBooks function?
you is import axiosInstance from '...' or using useContext?

Thank you very much.