I often see code when using redux-thunk, the inner function returning something, such as in the official Redux async example:
const fetchPosts = subreddit => dispatch => {
dispatch(requestPosts(subreddit))
return fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json => dispatch(receivePosts(subreddit, json)))
}
const shouldFetchPosts = (state, subreddit) => {
// return true or false
}
export const fetchPostsIfNeeded = subreddit => (dispatch, getState) => {
if (shouldFetchPosts(getState(), subreddit)) {
return dispatch(fetchPosts(subreddit))
}
}
so fetchPostsIfNeeded() is a thunk, and so is fetchPosts(). They both return a function, and the function returns something too. Now this function is actually called by the middleware, and I don't think the returned value is ever used. So why does the inner function inside the thunk keep on returning something instead of just invoking it? The code could have been:
const fetchPosts = subreddit => dispatch => {
dispatch(requestPosts(subreddit))
fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json => dispatch(receivePosts(subreddit, json)))
}
const shouldFetchPosts = (state, subreddit) => {
// return true or false
}
export const fetchPostsIfNeeded = subreddit => (dispatch, getState) => {
if (shouldFetchPosts(getState(), subreddit)) {
dispatch(fetchPosts(subreddit))
}
}