useLogin
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;
};Here is a description of each:
loading: A boolean flag that indicates whether the request for login is still in flight.login: The login request callback. It’s function that you need to call with the following parameters:usernameEmailis the user email.passwordis the user password andredirectUrlis the redirect path when the login request is successful.data: the login response data. It’s an object with the following attributes:generateAuthorizationCodeis an object that contains either the code or anerrormessage of the login attempt. You need to check these fields to see if the login request was valid or not (see Usage example for more context).error: if the login request has failed, it will return an instance ofApolloError.
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>
);
}It creates some state values to keep track of the user email and password fields. It then uses the useLogin hook and extracts the return values. Based on the return values, it will either disable some fields when loading=true or return an error message when data.generateAuthorizationCode.error is not empty.