0% found this document useful (0 votes)
7 views1 page

Authcontext

The document defines an authentication context using React's Context API, allowing for user state management. It includes functions for logging in, logging out, and updating user information, with data stored in local storage. The AuthProvider component wraps around children components to provide authentication state and methods via context.

Uploaded by

JOSHUA OSOGO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Authcontext

The document defines an authentication context using React's Context API, allowing for user state management. It includes functions for logging in, logging out, and updating user information, with data stored in local storage. The AuthProvider component wraps around children components to provide authentication state and methods via context.

Uploaded by

JOSHUA OSOGO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

// AuthContext.

jsx
import { createContext, useContext, useState, useEffect } from "react";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {


const [user, setUser] = useState(null);
const [token, setToken] = useState(null);

useEffect(() => {
const storedUser = localStorage.getItem('user');
const storedToken = localStorage.getItem('token');
if (storedUser && storedToken) {
setUser(JSON.parse(storedUser));
setToken(storedToken);
}
}, []);

const login = (userData, token) => {


localStorage.setItem('user', JSON.stringify(userData));
localStorage.setItem('token', token);
setUser(userData);
setToken(token);
};

const logout = () => {


setUser(null);
setToken(null);
localStorage.removeItem('user');
localStorage.removeItem('token');
};

const updateUser = (updatedUser) => {


setUser(updatedUser);
localStorage.setItem('user', JSON.stringify(updatedUser));
};

return (
<AuthContext.Provider value={{ user, token, login, logout, updateUser }}>
{children}
</AuthContext.Provider>
);
};

export const useAuth = () => useContext(AuthContext);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy