user109640
user109640

Reputation: 35

setState in reactjs inside success function not setting state

I am using a ParsePlatform as backend storage and reactjs as front end. I am able to get the parse data using Parse.Query but unable to use the returned values as I do not know how to set the state from the successfull fetching of results. I tried like this way inside componentDidMount()

import React from 'react'
import Parse from 'parse'
class ConferenceInfo extends React.Component {
    state={
        someData:null
    }
    componentDidMount(){
        this.getConferenceInfo()
    }
    getConferenceInfo(){
        var ConferenceListing = Parse.Object.extend("ConferenceListing");
        var cl = new Parse.Query(ConferenceListing);

        cl.get("8glBIjeRrC", {
            success: function(cl) {
                // The object was retrieved successfully.
                alert(cl.get("someData")) //it works
                //this.setState({someData:cl.get("someData")}) not working              
            },
            error: function(object, error) {
                // The object was not retrieved successfully.
                // error is a Parse.Error with an error code and message.
            }
        });
    }
    render() {
        return (
            <div>
                {this.state.someData} //no result
            </div>
        )
    }
}
export default ConferenceInfo

Upvotes: 3

Views: 506

Answers (1)

loelsonk
loelsonk

Reputation: 3596

This is because this is not in the same scope. You are calling it inside success property, function callback.

To get it working we need to bind this.

First Create constructor method.

constructor(props) {
  super(props);
  // Our new bind method ref
  this.change = this.change.bind(this);
}

Then add new method change

change(obj) {
  this.setState(obj);
}

Finally your success callback

success: function(cl) {
  // ...
  this.change({ someData: cl.get("someData") })           
},

Upvotes: 0

Related Questions