-
Notifications
You must be signed in to change notification settings - Fork 42
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This commit adds an AuthContext exposing the functions to get and set current auth status. The context is then used in the App component.
- Loading branch information
Showing
2 changed files
with
65 additions
and
1 deletion.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import { | ||
ReactElement, | ||
createContext, | ||
useCallback, | ||
useContext, | ||
useState, | ||
} from 'react'; | ||
|
||
export type User = { | ||
name: string; | ||
email: string; | ||
}; | ||
|
||
export type AuthContextProps = { | ||
getUser: () => User | null; | ||
login: () => void; | ||
logout: () => void; | ||
isLoggedIn: () => boolean; | ||
}; | ||
export const AuthContext = createContext<AuthContextProps>({ | ||
getUser: () => null, | ||
login: () => {}, | ||
logout: () => {}, | ||
isLoggedIn: () => false, | ||
}); | ||
|
||
// eslint-disable-next-line react-refresh/only-export-components | ||
export function useAuth() { | ||
return useContext(AuthContext); | ||
} | ||
|
||
export function AuthProvider({ children }: { children: ReactElement }) { | ||
const [user, setUser] = useState<User | null>(null); | ||
|
||
const login = useCallback(() => { | ||
setUser({ | ||
name: 'John Doe', | ||
email: '', | ||
}); | ||
}, []); | ||
|
||
const logout = useCallback(() => {}, []); | ||
|
||
const getUser = useCallback(() => { | ||
return user; | ||
}, [user]); | ||
|
||
const isLoggedIn = useCallback(() => { | ||
return !!user; | ||
}, [user]); | ||
|
||
return ( | ||
<AuthContext.Provider value={{ getUser, login, logout, isLoggedIn }}> | ||
{children} | ||
</AuthContext.Provider> | ||
); | ||
} |