Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - Why won't my handleLogout funtion work in my react app?

I am trying to implement user auth, using react, react redux, and axios. My problem right now is when I click my logout button on my header, I want it to remove both access and refresh tokens from local storage, that get set at login. With the code I have now, I get no errors, but nothing happens when logout button gets clicked.

My handleLogout function:

    const history = useHistory();

    const handleLogout = () => {
        logout(history);
    };

my logout action that the above function uses:

export const logout = (history) => (dispatch) => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    console.log('Made it here');
    dispatch({
        type: LOGOUT_SUCCESS,
    });
    history.push('/');
};

It seems to never reach this action as my console.log('made it here') never gets outputted.

material ui button with onClick set to use function:

<Button
color="primary"
variant="outlined"
className={classes.link}
onClick={handleLogout}
>
    Logout
</Button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since your logout function returns an arrow function, and that function expects an argument dispatch, you also need to pass-in that argument in order to work.

import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';

// inside your component
const history = useHistory();
const dispatch = useDispatch();

function handleLogout() {
    logout(history)(dispatch);
};

Depending on your implementation, you might also import your dispatch dependency directly, and not pass-in it as an argument, so you can avoid returning a function which returns another function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...