cupcakekid
cupcakekid

Reputation: 233

Set state after observe()

What's the best way to set state based on the data received from observe()?

It seems setting state via componentWillMount() won't work as observe() runs after this and the data isn't available to set state.

I'm using the observe function as advised when using Parse

E.g.:

var DragApp = React.createClass({
  getInitialState: function () {
    return {
      activeCollection : ''
    };
  },

 observe: function() {
    return {
      collections: (collectionsQuery.equalTo("createdBy", currentUser))
    };
  },

  _setactiveCollection: function(collection) {
    this.setState({
      activeCollection : collection
    });
  },

  componentWillMount: function () {
    var collection = this.data.collections[0];
    this._setActiveCollection(collection);
  },

)}

Upvotes: 1

Views: 175

Answers (2)

cupcakekid
cupcakekid

Reputation: 233

I went the wrong way about this.

I shouldn't be storing this.data into state. I can pass it into components via render.

To get round this.data not being ready before rendering, I make use of the ParseReact function pendingQueries() inside render. E.g.

if (this.pendingQueries().length > 0) {
    content = 'loading...'
} else {
    content = 'hello world I am' + this.data.name
}

Upvotes: 1

marcel
marcel

Reputation: 3149

Try:

var DragApp = React.createClass({

    observe: function() {
        var collections = collectionsQuery.equalTo("createdBy", currentUser);
        return {
          collections: collections,
          activeCollection: collections[0]
        };
    },

    render: function () {
        // do something with this.data.collections and/or this.data.activeCollection
    },

)}

Upvotes: 0

Related Questions