Created
September 15, 2024 03:29
-
-
Save reoxb/dd608d83d6cccb01b2d182d2158ac516 to your computer and use it in GitHub Desktop.
React - Context API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useContext } from 'react'; | |
import { AuthContext } from './AuthContext'; | |
const UserProfile = () => { | |
const { user, logout } = useContext(AuthContext); | |
return ( | |
<div> | |
<h2>Welcome, {user ? user.name : 'Guest'}</h2> | |
{user && <button onClick={logout}>Logout</button>} | |
</div> | |
); | |
}; | |
export default UserProfile; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useState } from 'react'; | |
// Create the AuthContext | |
const AuthContext = createContext(); | |
// Create a provider component | |
const AuthProvider = ({ children }) => { | |
const [user, setUser] = useState(null); | |
// Function to handle login | |
const login = (userData) => { | |
// Perform login logic and set the user state | |
setUser(userData); | |
}; | |
// Function to handle logout | |
const logout = () => { | |
// Perform logout logic and reset the user state | |
setUser(null); | |
}; | |
// Value object to be passed to consuming components | |
const authContextValue = { | |
user, | |
login, | |
logout, | |
}; | |
return ( | |
<AuthContext.Provider value={authContextValue}> | |
{children} | |
</AuthContext.Provider> | |
); | |
}; | |
export { AuthContext, AuthProvider }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment