DEV Community

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

Posted on

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.

Top comments (1)

Collapse
 
bhabukadhikari profile image
BhabukAdhikari

Nice information