useOnError
This hook can only be used if the authProvider
is provided.
useOnError
calls the onError
method from the authProvider
under the hood.
It returns the result of react-query
's useMutation, which includes many properties like isSuccess
and isError
.
Data that is resolved from the onError
will be returned as the data
in the query result with the following type:
type OnErrorResponse = {
redirectTo?: string;
logout?: boolean;
error?: Error;
};
According to the onError
method's returned values, the following process will be executed:
redirectTo
: If it has a value, the app will be redirected to the given URL.logout
: If it istrue
,useOnError
calls thelogout
method.error
: An Error object representing any errors that may have occurred during the operation.
Internal Usage
refine uses useOnError
internally in the data hooks to handle errors in a unified way.
When an error is thrown by any data hook, the useOnError
function is triggered with the error object. Afterward, the error object is passed to the onError
method of the authProvider
, which can be utilized to redirect the user or to log them out.
import type { AuthBindings } from "@refinedev/core";
const authProvider: AuthBindings = {
// ---
logout: () => {
// ---
return {
success: true,
redirectTo: "/login",
};
},
onError: (error) => {
const status = error.status;
if (status === 418) {
return {
logout: true,
redirectTo: "/login",
error: new Error(error),
};
}
return {};
},
// ---
};
For more information about data hooks, refer to the Data Provider documentation→
Usage
Let's say that a payment request was declined by the API. If the error status code is 418
, the user will be logged out for security reasons:
import { useOnError } from "@refinedev/core";
const { mutate: onError } = useOnError();
fetch("http://example.com/payment")
.then(() => console.log("Success"))
.catch((error) => onError(error));
We have a logic in authProvider
's onError
method like below.
import type { AuthBindings } from "@refinedev/core";
const authProvider: AuthBindings = {
// ---
logout: () => {
// ---
return {
success: true,
redirectTo: "/login",
};
},
onError: (error) => {
const status = error.status;
if (status === 418) {
return {
logout: true,
redirectTo: "/login",
error: new Error(error),
};
}
return {};
},
// ---
};
Any error passed to mutate
function will be available in the onError
in the authProvider
.