DEV Community

Calie Rushton
Calie Rushton

Posted on

Implementing client-side logout with React Router V4

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:

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.

Asking the right questions

It seemed to me like there were 2 things I had to do to make this work:

  1. Clear the token in localStorage
  2. Push the url for the homepage onto the history prop

I had this function in my Logout component and passed it to the button as a prop but when I clicked the button in the app, I got a TypeError: Cannot read property 'props' of undefined. How do I get those props defined? Do I have to pass them in somehow from somewhere?

As seems to be usual for me, the answer I wanted didn't present itself until I googled the right thing. I googled the error, and a couple of other things such as "react router redirect on logout", coming to the conclusion it was a scoping issue. So do I need to bind the function? Maybe I should export the Logout component using 'WithRouter'??

Obviously none of that worked so I thought, "What am I really trying to do here?". I have a button that says 'logout'. When that button is clicked, I want to redirect the user to the homepage. When I finally tried "react router 4 redirect on button click", this wonderfully simple (but effective) bit of code revealed itself on StackOverflow (where else?):

Thank you @lyubomir !! There were 2 lightbulb moments here for me:

  1. 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.
  2. There is another way to push the new entry onto the history prop besides writing 'this.props.history.push('/')'. The history prop is another thing for me to really get my head around / write another blog about.

What @lyubomir did which I especially liked was to extract the necessary bit of code from the full example on the react training site. I'd actually looked at this already but sometimes (especially if you are already confused) it can be tricky to identify the bit of code you're really looking for, and put it in the context of your own. I really love that these people are around to get us through when we are stuck!

So here's what my lovely Logout component looks like right now:

Vitally, it all works! Also, there was a nice reminder that another thing I wanted to do in this rebuild was to practise using destructuring a bit more. Next job for me, I think, is to look at the first use of nested routes in my app.

Top comments (3)

Collapse
 
gavinschriver profile image
gavinschriver • Edited

I made a dev account just to say thank you for this! Brand new to React (in a software bootcamp course rn) and was looking for a way to do this without using a <Link> to a <Route> component which was how we were taught but had the weird effect of flashing a "/logout" endpoint in the URL. I adapted this to hook-based functional component use 'cause they didn't bother teaching us classes at all.

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>;
};

Enter fullscreen mode Exit fullscreen mode
Collapse
 
calier profile image
Calie Rushton • Edited

Gavin, THANK YOU!!!

I have neglected this account for a while (especially the comments) but I'm really pleased to get your message and I'm so glad I could help. I'm honoured that you created your account to make a comment :)

Also it's really cool to see you used a functional component with a hook - hooks weren't a thing when I was at bootcamp so I missed out on those, hence the class component.

Hopefully you are still using the platform, sorry it took me 2 years to get back to you but better late than never right?!?!?!

Calie

Collapse
 
gpadbidri profile image
gpadbidri

Will it STILL be able to access the history, if I do a BROWSER BACK post logout ? I think yes ! I do not know how to clear HISTORY that way on Browser BACK button click, user does not see previous history URL's (we have taken care to show the UNAUTH screen to user ass tokens will not be available) for that site. But I want to get rid of the browsing history for the site (using CLASS Components)