Jumbo 6.x
Search…
⌃K

Implement Login Form

Implement the login functionality is fairly simple and straightforward. For that, you need to perform following steps:

Implement Login Form

It is up to you what form validation library you use. In Jumbo we are using Formik library for now but we are also planning to add react-hook-form library soon.

Define a signIn service

In this step, you will need to define a signIn service which would be a promise based function and will be responsible to call our post based signIn API. Here is an example of a signIn service:
authServices.signIn = async (loginCreds) => {
try {
return await jwtAuthAxios.post('/auth', loginCreds);
} catch (e) {
return e.response;
}
};
The above simple signIn service function accepts loginCreds in an object format with two keys (email,password) and then calls the post API /auth. Finally, it either returns an object with token key value pair on successful verification of the user Or returns an error.

Define an onSubmit handler

Now, getting back to the login form you develop. You will need to handle the submit event of the form to send the user input login credentials. Your onSubmit handler function would be something similar to the following:
import {useNavigate} from "react-router-dom";
import useJumboAuth from "@jumbo/hooks/useJumboAuth";
const Login = ({disableSmLogin}) => {
const {setAuthToken} = useJumboAuth();
const navigate = useNavigate();
const onSignIn = (email, password) => {
authServices.signIn({email, password})
.then((response) => {
if(response.status === 200) {
if(response?.data?.token) {
setAuthToken(response?.data?.token);
navigate("/dashboards/misc")
}
}
else {
setServerError({
message: response.data.error
});
}
});
};
return (
//...here your form rendering goes
)
};
export default Login;
So, you can handle the condition based on the response you receive from your service function and the time you receive the token successfully, you can store that with the setAuthToken function.
Once the token is stored then behind the scene Jumbo will automatically fill the authUser through the JumboAuthProvider and this authUser is now can be accessed anywhere in the app using useJumboAuth hook like shown below:
import useJumboAuth from "@jumbo/hooks/useJumboAuth";
function MyComponent() {
const {authUser, isLoading} = useJumboAuth();
return (
//... content to be rendered
)
}