1

I am not able to log out on button click and cannot work out why. I have a logout button on my header.(navigation)

I am new to React.

I have a folder called Store, with Auth-context file, I have a login and logout handler in app.js, I am importing AuthContext from ./store/auth-context.

I have no problems logging in, but I always have to do localStorage.clear() in the console to "logout".

In my Header component, I am calling as const isLoggedIn and onLogout with useContext(AuthContext).

On the bottom of the file in Header.js I have defined

    {isLoggedIn && (BasicButton onClick={onLogout}>log out<BasicButton>)}

Since onLogout is storing the logoutHandler, I cannot work out why this will not execute when button is clicked. I am also using React Router version 6.4.4
Auth Context
Handlers

1
  • 1
    Kindly add your code in the question only, instead of images Commented Jan 4, 2023 at 8:20

1 Answer 1

0

Maybe you forgot to wrap child elements with AuthContext Provider

// CONTEXT
const AuthContext = createContext()

const AuthContextProvider = ({children}) => {
   const [isLogin, setIsLogin] = useState(false);
   
   const login = () => {
      setIsLogin(true)
   }

   const logout = () => {
      setIsLogin(false)
   }
   
   return (
     <AuthContext.Provider value={{isLogin, login, logout}}>
            {children}
     </AuthContext.Provider>
   )
}

export {AuthContext, AuthContextProvider}

You should wrap it with index.js provider

<AuthContextProvider>
  <App/>
</AuthContextProvider >

Now you can access isLogin, login and logout functions in the component you want using useContext

const Navbar = () => {
   const {isLogin, login, logout} = useContext(AuthContext)
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.