I am learning redux and there is one thing puzzling me regarding the internal logic - how does a thunk receive dispatch
as argument if a thunk is an argument to dispatch
and not vice versa? Here is a sample code:
I am creating an action creator which is a thunk (it does not return an action itself but another function which eventually returns the action). I am defining it to receive dispatch
function as argument, like this (code is simplified to serve as example):
export const fetchPosts = () => {
return async (dispatch) => {
const response = await fetch('some url');
dispatch({type: 'FETCH_POSTS', payload: response});
}
}
Then I use this thunk in App.js file, when I am getting a dispatch
function from 'react-redux':
import { useDispatch } from 'react-redux';
import { fetchPosts } from './store/posts-actions';
function App() {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchPosts());
},[dispatch]);
...
}
I am not passing dispatch
as an argument to fetchPosts()
. I am passing fetchPosts()
to dispatch
. And this is the part that I don't understand.
How does fetchPosts
receive dispatch
as argument if fetchPosts
is an argument to dispatch
and not vice versa?