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)
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'
}
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
}
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
Lastly our customisable hook for fetching books.
function useGetBooks() {
return useQuery({
queryKey: ['books'],
queryFn: () => getBooks(),
})
}
Thank you for reading it ๐
Top comments (1)
how can use axiosInstance in getBooks function?
you is import axiosInstance from '...' or using useContext?
Thank you very much.