Finish the Authentication Flow
Add a logout function to the UserContext and a logged-in state to the LoginButton
In the previous lesson, you built the authentication form allowing users to register and log in.
This lesson will focus on finishing the authentication flow by:
Add logout function to
UserContext
Adding a logged-in state to the
LoginButton
Add Logout Function to ‘UserContext’#
The UserContext
needs a logout
function to clear the user and token states when the user logs out.
Start by adding the logout
function to the UserContext
type and initial state:
xxxxxxxxxx
interface UserContextProps {
user: User | null
token: string | null
setUser: React.Dispatch<React.SetStateAction<User | null>>
setToken: React.Dispatch<React.SetStateAction<string | null>>
login: (user: {
username: string
password: string
}) => Promise<void | string>
register: (user: {
username: string
password: string
}) => Promise<void | string>
logout: () => void
}
xxxxxxxxxx
export const UserContext = createContext<UserContextProps>({
user: null,
token: null,
setUser: () => {},
setToken: () => {},
login: async () => {},
register: async () => {},
logout: () => {},
})
Then, implement the logout
function inside the UserContext
provider:
xxxxxxxxxx
const logout = () => {
setUser(null)
setToken(null)
localStorage.removeItem("newma-events-token")
}
This lesson preview is part of the Sleek Next.JS Applications with shadcn/ui course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Sleek Next.JS Applications with shadcn/ui, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
