Skip to main content
Version: 3.xx.xx

useAuthenticated

useAuthenticated calls the checkAuth method from theauthProvider under the hood.

It returns the result of react-query's useQuery which includes many properties, some of which being isSuccess and isError.
Data that is resolved from the useAuthenticated will be returned as the data in the query result.

Usage

useAuthenticated can be useful when you want to ask for authentication to grant access to custom pages manually.

We have used this hook in refine's <Authenticated> component which allows only authenticated users to access the page or any part of the code.

We will demonstrate a similar basic implementation below. Imagine that you have public page but you want to make some specific fields private.

We have a logic in authProvider's checkAuth method like below.

const authProvider: AuthProvider = {
...
checkAuth: () => {
localStorage.getItem("username")
? Promise.resolve()
: Promise.reject(),
},
...
};

Let's create a wrapper component that renders children if checkAuth method returns the Promise resolved.

components/authenticated.tsx
import { useAuthenticated, useNavigation } from "@pankod/refine";

export const Authenticated: React.FC<AuthenticatedProps> = ({
children,
fallback,
loading,
}) => {
const { isSuccess, isLoading, isError } = useAuthenticated();

const { replace } = useNavigation();

if (isLoading) {
return <>{loading}</> || null;
}

if (isError) {
if (!fallback) {
replace("/");
return null;
}

return <>{fallback}</>;
}

if (isSuccess) {
return <>{children}</>;
}

return null;
};

type AuthenticatedProps = {
fallback?: React.ReactNode;
loading?: React.ReactNode;
};

Now, only authenticated users can see the price field.

components/postShow
import { Authenticated } from "components/authenticated"

const { Title, Text } = Typography;

export const PostShow: React.FC = () => (
<div>
<Authenticated>
<span>Only authenticated users can see</span>
</Authenticated>
</div>
)
caution

This hook can only be used if the authProvider is provided.