Gio Polvara
Gio Polvara

Reputation: 27018

Idiomatic Redux: Dispatch more than one action

I have a Redux application that shows a list of posts. The state is more or less this:

{
  posts: [
    {id: 1, title: 'My Post'},
    {id: 2, title: 'Also this one'},
    {id: 3, title: 'Other Post'}
  ],
  visible_post_ids: [1, 2]
}

Whenever I load some posts I add them to posts, then I replace the content of visible_post_ids.

This is my action creator for loading posts:

function loadPosts (filters) {
  return function (dispatch, getState) {
    return fetch(`/posts.json?filters=${filters}`)
      .then((response) => response.json())
      .then((posts) => {
        dispatch(postsLoaded(posts)) // Will update `posts`
        const postIds = posts.map((post) => post.id)
        dispatch(updateVisiblePosts(postIds)) // Will update `visible_post_ids`
      })
  }
}

My question is: is it idiomatic to dispatch two (or more) events from a thunk? Or should I dispatch only one and handle it in various reducers?

Upvotes: 0

Views: 205

Answers (2)

Exayy
Exayy

Reputation: 620

Quick answer : there is no problem to dispatch two or more actions from a thunk, I think it's a good practice,especially if API Call response contains answers to two completely different concerns.

I think it depends what you are trying to represent, in your case you can have one action that represent an add of new posts and two different reducers can catch it and do different tasks with it. But you can see that as two different actions (your example) and it's great too.

As Sergey L said, in your case with a unique action (for your case) it can create an interesting "dependency"

Upvotes: 2

Sergey L
Sergey L

Reputation: 1492

If you don't consider scenario when it is possible to postsLoaded without calling updateVisiblePosts, it is better to handle the state change just in postsLoaded. Especially if you need them to be in sync. For example, if you need a grantee that visible_post_ids does not contains Ids from not existing/loaded posts. Besides it minimizes the updates as each dispatch will cause processing in React.

On the other hand, having these actions separate can make code more clear as you have very simple implementation for each action.

Upvotes: 1

Related Questions