How to write logout function in functional component using reactjs?

Asked
Active3 hr before
Viewed126 times

8 Answers

usingwritelogoutfunctionalreactjscomponentfunction
90%

I'm new in creating functional components, in Class Components we declare logout function in this ,format but i don't know how to declare variable and how to write push to another functional component. , "push to another functional component" means routing? – VJR08 Mar 11 '20 at 5:51

React Router v4 has now added the useHistory hook for stateless / functional components. Sample snippet that would handle logout in your case

import { useHistory } from "react-router-dom";

function Logout() {
  let history = useHistory();

  function handleLogOut() {
    sessionStorage.setItem("userToken", '');
    sessionStorage.clear();
    history.push("/sigin"); // whichever component you want it to route to
  }

  return (
    <button type="button" onClick={handleLogOut}>
      Go home
    </button>
  );
}
load more v
88%

Create a user logout Component,In the above example code, you can see we created a “UserLogout” Class Component. Here we are rendering logout button but there is no logout function calling on button click.,Define logout function with class component

Pretag
 Pretag team - issue, fix, solve, resolve
72%

The fact I'm now using Routes threw me a little - I figured on having a Logout component containing a button, which is rendered by the AlbumsPage component (the AuthenticatedRoute) once the user is logged-in. I knew this didn't need it's own Route though, why would I need the URL of 'myapp/logout' or whatever? At this point I'm only handling authentication on the client side, which is just a matter of setting and clearing the token in localStorage. I'm going to figure out the server-side stuff later.,If you read my last post, you'll know I'm rebuilding the front-end of an app I built at the end of bootcamp, to use Routes instead of conditional rendering with state. I just implemented a button to log the user out of the app, and it took me longer than I was expecting, so here's what happened:,Seeing how to use Redirect on its own rather than in the render method of a route or any of that stuff. The react training site has more on that here.

export const LogoutButton = () => {

  const [loggedOut, setLoggedOut] = useState(false)

  const logout = () => {
    localStorage.removeItem("whpf_user")
    setLoggedOut(true)

  };

  if (loggedOut) {
    return <Redirect to="/login" push={true} />
  }

  return <Button onClick={logout}>LogOut</Button>;
};

65%

UserMenu functional component is the first component that uses our AuthenticationContext initialized in App. With button elements and their onClick methods we can login or logout our user by updating AuthenticationContext.,SiteNavbar component is the second component that uses AuthenticationContext. It displays our user using getUser() method from our authenticationService and renders UserMenu component.,User data is stored inside state in App component to force re-rendering for all components when user data are changed - user is logged in or logged out.

// ONLINE-RUNNER:browser;

//import React from 'react';
//import ReactDOM from 'react-dom';

const AuthenticationContext = React.createContext();

const UserMenu = () => {
    const authenticationService = React.useContext(AuthenticationContext);
  	const handleLoginClick = () => authenticationService.loginUser('john');
    const handleLogoutClick = () => authenticationService.logoutUser();
    return (
      <>
        <button onClick={handleLoginClick}>Login John!</button>
        <button onClick={handleLogoutClick}>Logout John!</button>
      </>
    );
};

const SiteNavbar = () => {
    const authenticationService = React.useContext(AuthenticationContext);
    return (
      <div>
        <span>{authenticationService.getUser()}</span>
        <UserMenu />
      </div>
    );
};

const App = () => {
  const [user, setUser] = React.useState(null);
  const authenticationService = {
      getUser: () => user,
      loginUser: (user) => {
          //TODO: Replace setUser with AJAX request to server
          setUser(user);
          return true;
      },
      logoutUser: () => {
          //TODO: Replace setUser with AJAX request to server
          setUser(null);
          return true;
      }
      // other methods ...
  };
  return (
    <AuthenticationContext.Provider value={authenticationService}>
      <SiteNavbar />
    </AuthenticationContext.Provider>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
75%

So come down above the return and below the dynamicLink function and right here let's create it, so I'm gonna say const handleSignOut and we'll make it an arrow function that doesn't take in any arguments and now let's call axios, so I'm gonna say axios.delete and the API endpoint we're gonna hit is gonna be https://api.devcamp.space and then it is /logout I believe. ,Now that we have this handleSignOut, we can actually call it from within our JSX code, so scroll down, all the way down to the bottom where you have your name here on the right-hand side div and we're gonna add a conditional because we don't want this sign out link to be shown unless a user is signed in, it wouldn't make any sense for a guest user to see a sign-out link.,Now let's also test out, we're not getting the error but let's make it's also working. So, I'm gonna say auth, let's test out the redirect, so I'll say my Login and let's say that we're on the Blog page, we're in it, we're able to see it and then it's time to sign out.

const handleSignOut = () => {
   axios.delete("https://api.devcamp.space/logout", {
      withCredentials: true
   })
};
load more v
40%

Make sure to add it below the export default function Login() { line.,We are going to use the useHistory hook that comes with React Router. This will allow us to use the browser’s History API., Add the useHistory hook in the beginning of App component.

const history = useHistory();
load more v
22%

Working with Redux Actions, Reducers, Store for Application state,Creating React Function Components with Hooks & Form Validation,If you need Form Validation with React Hook Form 7, please visit: React Form Validation with Hooks example

Pretag
 Pretag team - issue, fix, solve, resolve
60%

Function-based component example:,Class-based component example:,Call the tokenManager.clear (opens new window) method on the oktaAuth (opens new window) instance. The useOktaAuth (opens new window) React Hook (opens new window) or withOktaAuth (opens new window) higher-order component (opens new window) makes this object easily available within your components.

import React from 'react';
import { useOktaAuth } from '@okta/okta-react';

// Basic component with logout button
const Logout = () => {
  const { oktaAuth } = useOktaAuth();

  const logout = async () => {
    oktaAuth.tokenManager.clear();
  };

  return (
    <a onClick={logout}>Logout</a>
  );
};

export default Logout;
load more v

Other "using-write" queries related to "How to write logout function in functional component using reactjs?"