0
votes

I'm using Mongo/Meteor 1.3/React. In my simple example I use an wrapper React component to query the Mongo collection and create an Array. When passing to the Child component, it seems like the Array object is not ready when constructor is called - meaning I can't access the props.

This feels like it must be a common problem. Should I be using a different React Lifecycle Component? Or adding some form of waitOn function? Any advice appreciated!!

Parent Component

export default class BulkMapWrapper extends TrackerReact(React.Component) {

constructor() {
super();
const subscription =  Meteor.subscribe("listing",{sort: {_id:-1}})
this.state = {
eventsData: subscription
}
}


render () {
var markerArray = []
markerArray = ...


return(
<div className="panel panel-default">
<div className="panel-body">
<FourthMap
mapParams = {manyEvents}
markers = {markerArray}
 />
</div>
</div>
)

Child Component

export default class GooleMapComponent extends Component {
constructor(props){
super(props)
console.log(this.props.markers);
1
is this line Meteor.subscribe("listing",{sort: {_id:-1}}) asynch? - StateLess
I believe this is not asynchronous, I tested this by adding the following line this.state = { ready: subscription.ready(), eventsData: subscription } . this.state.ready remains at false although I can query the collection from console... - ElJefeJames

1 Answers

1
votes

You should use the componentDidMount function to get the data and then set a new state with the resulting data.

class GetData extends React.Component {
  constructor(props) {
   super(props);
   this.state = {};
  }

  componentDidMount() {
     const subscription =  Meteor.subscribe("listing",{sort: {_id:-1}});

     this.setState({
       eventsData: subscription
     });
  }
}

You can then pass down the state from the GetData component as props to its children or explicitly to another component in the render function.

This is generally how you should handle AJAX requests in React but I'm not sure if this will translate well to use in Meteor.