DEV Community

Vicky Vasilopoulou
Vicky Vasilopoulou

Posted on

7

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 πŸ˜€

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay