Axios π
Udemy John
GET Request
we can do either axios.get(url) or axios(url) for GET request.
import { useEffect } from 'react'
// limit, if 429 wait for 15 min and try again
import axios from 'axios'
const url = 'https://course-api.com/react-store-productss'
const fetchData = async () => {
try {
const { data } = await axios(url)
console.log(data)
} catch (error) {
// if you just do error here, it won't show you the object
console.log(error.response)
}
}
const FirstRequest = () => {
useEffect(() => {
fetchData()
console.log('first axios request')
}, [])
return <h2 className="text-center">first request</h2>
}
export default FirstRequest

Headers
We need to provide headers for POST and PATCH request. Some times in some apis we also need to provide headers for GET request.
POST Request
Global Defaults
We can add global defaults to axios. That means every time we make a axios request, that functionality will be added. For example, we can add these defaults in one file and import them
Let's say we add first one (headers), then every request will accept application/json and we don't need to add to individual requests.
We need to create a new JS file for axios configuration like this
We have created axios folder and inside that, we have a file global.js where all axios defaults go.
Then we need to import this file in main file App.js or index.js like this
Now we can use axios in the component file as ususal
both resp1 and resp2 will have request headers - application/json because of global settings of axios. We might not need this setting to one of the individual axios request sometimes, so let's see how to solve that using custom instance
Custom Instance
Here instead of global instance we use custom instance where we can create axios functions that have some defaults and we can use it where we want
The below request has application/json

The below second request is a normal axios request so it has both application/json and text

Interceptors
These are the axios functions that can be called before the request is sent and/or after getting the response.


Interceptors make more sense when we have complex applications for example if we have authentication in a big app. This is just an intro to interceptors and we can take a look later in projects as and when we need (I'll update this notes with more info as I come across it)
We will use CustomImplementation of axios and not global one in our example. We could also use Global ones, just fyi.
Component that uses interceptor that is used in App.js
The request and response interceptors in authFetch
Now where this interceptors comes in handy? We can think of Authentication as one use-case.
Let's say if we get some type of response from backend, it will hit response interceptor. If the user is not logged in, then we get the 401 which can be caught in this response interceptor and we can log out the user immediately and set the state accordingly.
Last updated
Was this helpful?