Making an API call using Axios Login Authentication

In the second part of the React Login authentication, we’ll take a look at how we can make our login form functional.

We’ll collect the user’s input data via the login form and then send that data to our API.

we will use one of the Public APIs for this tutorial called reqres

So let’s get started.

Axios Login Authentication

Step 01

The first step is to install Axios.

Axios is a promise-based HTTP client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.


npm install axios

Step 02

So in the second step after the successful installation of axios now it’s time to collect the data from our users and store it in our react hook which is values that we have created in our first article here. so we have an object in our react hook values so now we need to update email and pass inside our object whenever the users will put up their email and pass.

const [values, setValues] = useState({
	email: "",
	pass: "",
	showPass: false,
});

So now in our input/text fields, we need to call the onChange function to update our hook i.e

For email address:

<TextField
type="email"
fullWidth
label="Enter your email"
placeholder="Email Address"
variant="outlined"
required
onChange={(e) => setValues({ ...values, email: e.target.value })}
/>

For Password:
<TextField
type={values.showPass ? "text" : "password"}
fullWidth
label="Password"
placeholder="Password"
variant="outlined"
required
onChange={(e) => setValues({ ...values, pass: e.target.value })}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton onClick={handlePassVisibilty}
aria-label="toggle password" edge="end">
{values.showPass ? <VisibilityOffIcon /> : <VisibilityIcon />}
</IconButton>
</InputAdornment>),
}}
/>

So after getting and storing the data from the users in our hook now it’s time to submit the login form.

so let’s create a function which we will call onSubmit the function name could be anything let’s say handleSubmit inside this function we will make an API call

in the below code snippet we are making an API Post request to https://reqres.in/api/login

In case of success, we are receiving a token from API and then we are storing that token in our browser localStorage


const handleSubmit = (e) => {
	e.preventDefault();
	axios.post("https://reqres.in/api/login", {
			email: values.email,
			password: values.pass,
		})
		.then((res) => {
			localStorage.setItem("token", res.data.token);
			navigate("/dashboard");
		})
		.catch((err) => console.error(err));
};

Complete source code:

import {
	Container,
	Button,
	Grid,
	Paper,
	TextField,
	IconButton,
	InputAdornment,
} from "@mui/material";
import VisibilityIcon from "@mui/icons-material/Visibility";
import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";
import React, { useState } from "react";
import axios from "axios";


const Login = () => {

const [values, setValues] = useState({
	email: "",
	pass: "",
	showPass: false,
});

const handleSubmit = (e) => {
	e.preventDefault();
	axios
		.post("https://reqres.in/api/login", {
			email: values.email,
			password: values.pass,
		})
		.then((res) => {
			localStorage.setItem("token", res.data.token);
		})
		.catch((err) => console.error(err));
};
const handlePassVisibilty = () => {
	setValues({
		...values,
		showPass: !values.showPass,
	});
};

	return (
		<div>
<Container maxWidth="sm">
<Grid
	container
	spacing={2}
	direction="column"
	justifyContent="center"
	style={{ minHeight: "100vh" }}
>
<Paper elelvation={2} sx={{ padding: 5 }}>
<form onSubmit={handleSubmit}>
<Grid container direction="column" spacing={2}>
	<Grid item>
		<TextField
			type="email"
			fullWidth
			label="Enter your email"
			placeholder="Email Address"
			variant="outlined"
			required
			onChange={(e) => setValues({ ...values, email: e.target.value })}
		/>
	</Grid>

	<Grid item>
	<TextField
		type={values.showPass ? "text" : "password"}
		fullWidth
		label="Password"
		placeholder="Password"
		variant="outlined"
		required
		onChange={(e) => setValues({ ...values, pass: e.target.value })}
		InputProps={{
			endAdornment: (
				<InputAdornment position="end">
					<IconButton
						onClick={handlePassVisibilty}
						aria-label="toggle password"
						edge="end"
					>
						{values.showPass ? <VisibilityOffIcon /> : <VisibilityIcon />}
					</IconButton>
				</InputAdornment>
			),
		}}
	/>
	</Grid>

	<Grid item>
	<Button type="submit" fullWidth variant="contained">
		Sign In
	</Button>
	</Grid>
</Grid>
</form>
</Paper>
</Grid>
</Container>
		</div>
	);
};

export default Login;

Last Part of the series

Handle Protected Routes in React using Local Storage