Fabian Bosler Fabian Bosler - 5 months ago 28
React JSX Question

How can I access Redux State in createContainer (react-meteor-data)?

Stack: Meteor 1.5, React, Redux, React Router 4

I am trying to display a selection of events in a React component. The events should be filtered based on some Redux state. The filtering should happen server side (to minimize traffic) - i.e. via parameters in the subscription.

Now I don't want all my Meteor date in the Redux state, but only some general application settings (user settings, filter, location and such).

My approach is the following:


  1. Connect a dumb component with Redux state and get filter

  2. Wrap connected component in createContainer and pass props (which should include filter).



My Problem is:

Props don't include filter. Anybody knows why? Code is below. The console log only displays props of the Home component (i.e. the unconnected component).

class Home extends Component {
render () {
return (
<div>
{ /* display events here */ }
</div>
)
}
}

const mapStateToProps = state => {
return {
filter: state.filter
}
}

let connectedHomeComponent = connect(mapStateToProps,)(Home)

export default connectedHomeContainer = createContainer(_ => {
console.log(_);
let eventsSub = Meteor.subscribe('getEventsByFilter');
let loading = !eventsSub.ready();
let events = null;
loading ? (events = null) : (events = Events.find().fetch());
let eventsExists = !loading && !!events;
return {
loading,
events,
eventsExists,
}
}, connectedHomeComponent)

Answer Source

You wrapped your Home component in the wrong order. Your callback function gets passed the props that your HomeContainercomponent gets passed. So if you want redux to inject the filter prop into your HomeContainer then you have to turn it around:

const HomeContainer = createContainer(_ => {
    console.log(_);
    const eventsSub = Meteor.subscribe('getEventsByFilter');
    const loading = !eventsSub.ready();
    let events = null;
    loading ? (events = null) : (events = Events.find().fetch());
    const eventsExists = !loading && !!events;
    return {
        loading,
        events,
        eventsExists,
    } }, Home)

export default connectedHomeContainer = connect(mapStateToProps)(HomeContainer)

Side Note: Use const as a default and only change it to let if you need to mutate the variable later on.