Skip to main content

useLogin Reference

useLogin is a React hook that facilitates login to your headless WordPress site without having to leave your Faust app.

API

The useLogin exports, defined as a TypeScript type:

type UseLogin = {
loading: boolean;
login: (
usernameEmail: string,
password: string,
redirectUrl?: string,
) => void;
data:
| {
generateAuthorizationCode: {
code?: string;
error?: string;
};
}
| undefined;
error: ApolloError | undefined;
};

Usage

Below is a full example of login to your WordPress site without leaving your Faust app. Upon a successful login, you will be redirected to /dashboard:

import { useLogin } from '@faustwp/core';
import { useState } from 'react';

export default function Login() {
const [usernameEmail, setUsernameEmail] = useState('');
const [password, setPassword] = useState('');
const { login, loading, data, error } = useLogin();

return (
<form
onSubmit={(e) => {
e.preventDefault();

login(usernameEmail, password, '/dashboard');
}}>
<fieldset>
<label htmlFor="usernameEmail">Username or Email</label>
<input
id="usernameEmail"
type="text"
disabled={loading === true}
value={usernameEmail}
onChange={(e) => setUsernameEmail(e.target.value)}
/>
</fieldset>

<fieldset>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
disabled={loading === true}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</fieldset>

{data?.generateAuthorizationCode.error && (
<p
dangerouslySetInnerHTML={{
__html: data.generateAuthorizationCode.error,
}}
/>
)}

<fieldset>
<button type="submit">Login</button>
</fieldset>
</form>
);
}