Christian February 2016

Dispatch different actions in redux

I have a (React) container component. It's children need different data from different api endpoints, so I want to dispatch 2 actions the same time (both are asynchronous).

This doesn't seem to be possible. If I have both dispatches, the activeSensors are always empty...

class Dashboard extends React.Component {

  static propTypes = {
    userData: React.PropTypes.array.isRequired,
    activeSensors: React.PropTypes.object.isRequired
  };

  static contextTypes = {
    store: React.PropTypes.object
  };

  constructor(props) {
    super(props);
  }

  componentWillMount() {
    const { store } = this.context;
    store.dispatch(fetchActiveSensorDataForAllSensors());
    store.dispatch(fetchUserData());
  }

  render() {
    return (
      <div>
        <AnalyticsPanel activeSensors={this.props.activeSensors}/>
        <SearchCustomer userData={this.props.userData}/>
      </div>
    );
  }
}

export default connect((state)=> {
  return {
    userData: state.userData.data,
    activeSensors: state.activeSensorsAll.sensors
  }
})(Dashboard);

EDIT: See the source for the full component.

Answers


Nathan Hagen February 2016

I haven't used the this.context.store.dispatch method your code uses, but I don't think that its necessarily the way you should be doing things. Primarily because it really muddies the line between container and presentational components. Presentational components don't need access to store, and there are other methods to do this which don't have this (albeit pedantic) drawback.

My component files typically look like this:

import React from 'react';
import { connect } from 'react-redux';
import * as actions from './actions';

export class Container from React.Component {
  componentWillMount() {
    // Most conical way

    const { fetchActiveSensorDataForAllSensors, fetchUserData } = this.props;
    fetchActiveSensorDataForAllSensors();
    fetchUserData();

    // Less conical way
    // const { dispatch } = this.props;
    // const { fetchActiveSensorDataForAllSensors, fetchUserData } = actions;
    // dispatch(fetchActiveSensorDataForAllSensors());
    // dispatch(fetchUserData());
  }

  render() {
    return (
      <div>
        <AnalyticsPanel activeSensors={this.props.activeSensors}/>
        <SearchCustomer userData={this.props.userData}/>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    activeSensors: state.activeSensorsAll.sensors,
    userData: state.userData.data
  }
}

export default connect(mapStateToProps, actions)(Container);

Post Status

Asked in February 2016
Viewed 2,285 times
Voted 14
Answered 1 times

Search




Leave an answer