Version: 4.xx.xxSource Code
useOnError
caution
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, some of which being 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;
};
redirectTo
: If has a value, the app will be redirected to the given URL.logout
: If istrue
,useOnError
calls thelogout
method.error
: An Error object representing any errors that may have occurred during the operation.
Usage​
Imagine that we make a payment request which is 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));
Any error passed to
mutate
function will be available in theonError
in theauthProvider
.
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 {};
},
// ---
};