Reputation: 33
I have tried to implement a simple logout functionality using "useDispatch" hook. I am using 'redux-thunk' as middleware. I want to change isAuthenticated in my state using Logout button to false. but I encounter this error:
TypeError: dispatch is not a function
// Logout action:
export const logout = () => dispatch => {
dispatch({ type: LOGOUT });
};
// Logout reducer:
case 'LOGOUT':
localStorage.removeItem('token');
return {
...state,
token: null,
isAuthenticated: false,
loading: false
};
// inside component:
const dispatch = useDispatch();
<a onClick={dispatch(logout)} href='#!'>
this way of using 'useDispatch' worked just fine when I implemented axios in async format. there is a hint when I hover on useDispatch which states:
Note for redux-thunk users: the return type of the returned dispatch functions for thunks is incorrect. However, it is possible to get a correctly typed dispatch function by creating your own custom hook typed from the store's dispatch function like this: const useThunkDispatch = () => useDispatch();
I dont know how can I fix this error: TypeError: dispatch is not a function
P.S: this is my first question in stackoverflow. :)
many thanks
Upvotes: 3
Views: 3458
Reputation: 2715
Welcome to SO. Look at this line:
<a onClick={dispatch(logout)} href='#!'>
The dispatch(logout)
part is executing immediately rather than providing a function for onClick
to execute. You need to do this:
<a onClick={() => dispatch(logout)} href='#!'>
Which is an anonymous function that doesn't execute immediately, but only gets executed by the onClick
event.
Upvotes: 3