useOnError is a hook that calls the onError method from the authProvider under the hood. It’s used to handle authentication errors, typically for scenarios like token expiration or unauthorized access.
Usage
import { useOnError } from "@refinedev/core";
const { mutate: onError } = useOnError();
// Call when an error occurs
onError(error);
Return Values
Returns a mutation result from @tanstack/react-query.
A function to trigger the error handling mutation. Accepts an error object as a parameter.
An async version of mutate that returns a Promise.
Indicates whether the error handling is in progress.
Indicates whether the error was handled successfully.
Indicates whether the error handling encountered an error.
The response from the error handler.Indicates whether the user should be logged out.
The URL to redirect to after handling the error.
Examples
Basic Usage
import { useOnError } from "@refinedev/core";
const MyComponent = () => {
const { mutate: onError } = useOnError();
const handleApiError = (error: any) => {
// Check if error is authentication related
if (error.statusCode === 401) {
onError(error);
}
};
return <div>...</div>;
};
With Data Provider
This hook is commonly used internally by Refine’s data hooks to handle authentication errors:
import { useCustom, useOnError } from "@refinedev/core";
const MyComponent = () => {
const { mutate: onError } = useOnError();
const { refetch } = useCustom({
url: "https://api.example.com/data",
method: "get",
});
const handleFetch = async () => {
try {
await refetch();
} catch (error) {
// Handle authentication errors
onError(error);
}
};
return <button onClick={handleFetch}>Fetch Data</button>;
};
Handling Token Expiration
import { useOnError } from "@refinedev/core";
import axios from "axios";
const MyComponent = () => {
const { mutate: onError } = useOnError();
// Add axios interceptor to handle errors globally
React.useEffect(() => {
const interceptor = axios.interceptors.response.use(
(response) => response,
(error) => {
// Handle 401 Unauthorized errors
if (error.response?.status === 401) {
onError(error);
}
return Promise.reject(error);
}
);
return () => {
axios.interceptors.response.eject(interceptor);
};
}, [onError]);
return <div>...</div>;
};
Custom Error Handling
import { useOnError } from "@refinedev/core";
const MyComponent = () => {
const { mutate: onError, data } = useOnError();
const handleError = (error: any) => {
onError(error);
};
React.useEffect(() => {
if (data?.logout) {
console.log("User will be logged out");
}
if (data?.redirectTo) {
console.log(`Redirecting to: ${data.redirectTo}`);
}
}, [data]);
return <div>...</div>;
};
Notes
- This hook is typically used internally by Refine’s data hooks
- If the
authProvider does not implement the onError method, this hook will return an empty response
- When
logout is true in the response, the hook automatically calls the useLogout hook
- When
redirectTo is provided, the hook automatically navigates to that path