Handle 401 with React Query Cleanly
Here’s how you can handle the 401 unauthorized error for network calls when using react query
Handling HTTP errors is a crucial part of building any web application. When an API returns an HTTP error status code, it’s important to handle it properly on the client side. In this blog post, we’ll take a look at two ways to handle 401 errors with React Query.
React Query is a popular library for managing data fetching and caching in React applications. It provides an easy-to-use API for fetching data and caching the results. React Query also provides built-in error handling that allows you to easily handle HTTP errors like 401 errors.
Method 1: Using onError
callback with query client
To handle 401 errors with React Query, we can use the onError
option. This option is available on both the QueryClient
and useQuery
hooks.
Let’s start by looking at how to use the onError
option with the QueryClient
.
import { QueryClient, QueryClientProvider } from 'react-query'
const queryClient = new QueryClient({
defaultOptions: {
onError: (error) => {
if (error.response.status === 401) {
// Handle 401 error here
}
},
},
})
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your app code here */}
</QueryClientProvider>
)
}
In the above code, we create a new instance QueryClient
and pass it to the QueryClientProvider
. We also set defaultOptions
for the QueryClient
. The defaultOptions
object contains a onError
function that gets called whenever an error occurs during a query.
In the onError
function, we check if the error response status is 401. If it is, we can handle the error as needed. For example, we might redirect the user to a login page, or display an error message.
Now let’s take a look at how to use the onError
option with the useQuery
hook.
import { useQuery } from 'react-query'
function MyComponent() {
const { data, error } = useQuery('myQuery', fetchData, {
onError: (error) => {
if (error.response.status === 401) {
// Handle 401 error here
}
},
})
if (error) {
return <div>{error.message}</div>
}
return <div>{data}</div>
}
In the above code, we use the useQuery
hook to fetch data from the API. We also pass the onError
option to the hook. The onError
function gets called whenever an error occurs during the query.
Inside the onError
function, we check if the error response status is 401. If it is, we can handle the error as needed. For example, we might redirect the user to a login page, or display an error message.
If an error occurs during the query, the error
object will be set. We can check for the presence of this object and display an error message to the user.
Method 2: Method 2: Using Axios Interceptors
Another way to handle 401 errors with React Query is to use an Axios interceptor. Axios is a popular HTTP client library that allows you to make HTTP requests from your application. By adding an interceptor, you can intercept all outgoing requests and handle errors like 401 errors in a centralized location.
To use an interceptor with React Query, you can create an Axios instance and use it to configure your QueryClient
. Here's an example:
import axios from 'axios';
import { QueryClient, QueryClientProvider } from 'react-query';
const api = axios.create({
baseURL: 'https://api.example.com',
});
api.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
// handle 401 error here
}
return Promise.reject(error);
},
);
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: async ({ queryKey }) => {
const response = await api.get(queryKey[0]);
return response.data;
},
},
},
});
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your app code here */}
</QueryClientProvider>
)
}
In the above code, we create a new Axios instance and add an interceptor to it. The interceptor checks if the response status is 401 and handles it as needed. We then create a new QueryClient
and configure it to use our custom Axios instance.
The defaultOptions
object contains a queries
property, which we use to set the queryFn
option for all queries. The queryFn
function is called whenever a query is executed, and it uses our custom Axios instance to make the request.
With this approach, all outgoing requests made through React Query will be intercepted by our Axios instance, and any 401 errors will be handled in a centralized location.
In conclusion, handling 401 errors with Axios interceptors and React Query is a powerful approach that allows you to handle errors in a centralized location. This makes it easy to handle errors consistently across your application and avoids the need to handle errors in multiple locations.
If you found this blog valuable, please consider giving it a clap to help spread it to other developers who may also find it interesting. Thank you for your time!