ProgrammingNoob221
ProgrammingNoob221

Reputation: 13

How to dispatch numerous actions using a single dispatch in React?

I am working on a project and still learning React. So currently, I have the following in my function. I was told that having numerous dispatches like so can cause problems, apart from looking messy and was suggested to create a single dispatch. How would I go about doing that?

dispatch({
      type: 'UPDATE_ARRAY',
      orderItemsArray: newitemsArray,
    });
    dispatch({
      type: 'UPDATE_NUMBER',
      tickNumber: tickNumber,
    });
    dispatch({
      type: 'UPDATE_MESSAGE',
      message: orderMessage,
    })

Upvotes: 0

Views: 146

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Calling dispatch on forEach should work.

const actions = [{
      type: 'UPDATE_ARRAY',
      orderItemsArray: newitemsArray,
    },{
      type: 'UPDATE_NUMBER',
      tickNumber: tickNumber,
    },{
      type: 'UPDATE_MESSAGE',
      message: orderMessage,
    }]

actions.forEach(action => dispatch(action));

Upvotes: 1

pr96
pr96

Reputation: 1211

Use redux-batched-actions.

    const mapDispatchToProps = (dispatch) => ({
  action2: id => dispatch(Actions.action2(id)),
  action3: id => dispatch(Actions.action3(id)),
  action1: (dateId, attrId) =>
    dispatch(batchActions([
      Actions.action2(dateId),
      Actions.action3(attrId)
    ]))
});

When used out of the box without any performance optimisations, there are two primary concerns: React will re-render multiple times React Redux will re-evaluate selectors multiple times

Upvotes: 1

Related Questions