0

I'm trying to grok Redux's async Reddit API example code

But I'm having a really hard time understanding what's going on with these two functions:

//action
function shouldFetchPosts(state, subreddit) {
  const posts = state.postsBySubreddit[subreddit]
  if (!posts) {
    return true
  } else if (posts.isFetching) {
    return false
  } else {
    return posts.didInvalidate
  }
}

//reducer 
function postsBySubreddit(state = {}, action) {
  switch (action.type) {
    case INVALIDATE_SUBREDDIT:
    case RECEIVE_POSTS:
    case REQUEST_POSTS:
      return Object.assign({}, state, {
        [action.subreddit]: posts(state[action.subreddit], action)
      })
    default:
      return state
  }
}

In particuar, postsbySubreddit[subreddit]; I've never seen a function accessed with subscript notation, and doesn't that function require a parameter when it's called?

1 Answer 1

1

state.postsBySubreddit is not a function, it's the name of the attribute in the store where the postsBySubreddit reducer function stores it's state.

If you had a system with 3 reducers, r1(), r2() and r3() then the store would have 3 attributes where these reducers store their data: store.r1, store.r2 and store.r3.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh I see, and the state of those attributes corresponds to the output of those functions I take it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.