Why when using redux-thunk, the inner function returns something?

Viewed 210

I often see code when using redux-thunk, the inner function returning something, such as in the official Redux async example:

The code:

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))
  }
}
1 Answers

It returns a promise that allows you to add a callback in then chain and do something when, as in the exaple, a subredit post is fetched.

export const fetchPostsIfNeeded = subreddit => (dispatch, getState) => {
  if (shouldFetchPosts(getState(), subreddit)) {
    dispatch(fetchPosts(subreddit)).then(() => doSomething());
  }
}
Related