JGM
JGM

Reputation: 83

meteor-reactjs: in constructor collection is empty

Due to the fact that I am new in meteor/react I can't figure out how to initialize my state variable.

My problem is that I would like to get

  1. my mongo collection through the createContainer from react-meteor-data (as described here),
  2. use the initialized prop to intialize the state variable

But the prop in the constructor is empty. Only when I the "gotClicked" function is called the prop.allLists is filled with the data from mongo.

Does anyone know why? My guess the data is loaded asynchronously, so that the data is not available yet in the constructor. What would be a better way to get the data?

import React, {Component, PropTypes} from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import {AllLists} from '../api/alllists.js'
export default class MyList extends Component {

    constructor(props) {
        super();

        console.log(props.allLists)
        console.log(this.props.allLists)
        //allLists is empty

        this.state = {
            lists: props.allLists
        }
    }

    gotClicked(){
        console.log(this.props.allLists)
        //allLists is filled
    }

    render() {
        return (
            <div className="container" onClick={this.gotClicked.bind(this)}>
            </div>
        );
    }
}

MyList.propTypes = {
   allLists: PropTypes.string.isRequired
}

export default createContainer(() => {
    return {
        allLists: AllLists.find({}).fetch()
    };
}, MyList);

Upvotes: 3

Views: 632

Answers (1)

aedm
aedm

Reputation: 6564

You're right, the data is loaded asynchronously, and it might not be available in the constructor. However, the callback function you pass to createContainer is evaluated again when the data is loaded, and it automatically updates the props of your component.

To catch this change, implement the componentWillReceiveProps function in your React component.

componentWillReceiveProps(nextProps) {
  this.setState({
    lists: nextProps.allLists
  });
}

Docs here: https://facebook.github.io/react/docs/component-specs.html

Upvotes: 2

Related Questions