DEV Community

Cover image for Token based authentication with local storage in React js with UseContext and useState
Rajiv Chaulagain
Rajiv Chaulagain

Posted on

10

Token based authentication with local storage in React js with UseContext and useState

Authentication in react js with api is a most common for any front end developers.

So at first create an context so that we could save token and use user data all across the application

import { createContext, useState } from "react";
export const AuthContext = createContext();

export const ProvideAuth = ({ children }) => {
export const getSession = () => {
return JSON.parse(localStorage.getItem('session'));
};

/**
* setToken from localstorage
*/

export const setSessionInLocalStorage = (token) => {
localStorage.setItem('session', JSON.stringify(token))
return true
};

const auth = getSession();
const [session, setSession] = useState(auth || '');
const setAuth = (token) => {
setSession(token);
setSessionInLocalStorage(token);
};
const { user, token } = session;
return (
<AuthContext.Provider value={{ user, token, setAuth }}>
{children}
</AuthContext.Provider>
)
};
Enter fullscreen mode Exit fullscreen mode

Now create a custom hook with useAuth.

import { useContext } from "react";
import { AuthContext } from "../context/ProvideAuth";
export const useAuth = () => {
return useContext(AuthContext);
};

Enter fullscreen mode Exit fullscreen mode

Now create a login page and set token while user login.

import React from "react";
import { Link, useHistory } from "react-router-dom";
import { toast } from 'react-toastify';
import { authenticationService } from '../../../services/api/authentication';
import { useAuth } from '../../../hooks/useAuth'
const UserLogin = () => {
const { setAuth } = useAuth();
return (
<button onClick={() => setAuth(token)}>Login</button>
);
};
export default UserLogin;
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is a simple trick and more code and logic will be provided in github.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
bhabukadhikari profile image
BhabukAdhikari

Nice information

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more