Log out when click on Link with React

Viewed 1354

I would like a log out function to be executed directly when a user clicks on a Link and without clicking on a Logout button (2 actions to 1 action).

I've got this link + this route:

<Link to="/logout">Logout</Link>
...
<Route path="/logout">
    <Logout />
</Route>

The logout component : do I really need one component just to call a "one line" function?

import React, { Component } from 'react'
import { logout } from './../../services/auth.service';
import { Redirect } from 'react-router-dom';

export default class Logout extends Component {
    state = {
        navigate: false
    }

    handleLogout() {
        logout();
        this.setState({
            navigate: true
        })
    }
    render() {
        const { navigate } = this.state;

        if (navigate) {
            return <Redirect to="/login" push={true} />;
        }
        return <button onClick={() => this.handleLogout()}>LOGOUT</button>
    }
}

I put all login(), register(), getData(), postData() logic inside services and even logout(), in auth.service.js:

export function logout() {
  localStorage.removeItem('user');
}

Do you know how can I do this "no button click" log out shortcut please ?

Thank you for your help.

[EDIT]

It seems that a function can be called when clicking the link with this:

<Link to="/logout" onClick={() => this.logout()}>Logout</Link>

Why isn't this mentioned in the React router documentation ?

This solution is not right because I still don't want to need using a logout component...

0 Answers
Related