SetState in reactjs inside success function not setting state

I am using ParsePlatform as backend storage and react as front-end. I can get the parsing data using Parse.Query, but was unable to use the return values โ€‹โ€‹as I don't know how to set the state from a successful fetch of the results. I tried 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

      

+3


source to share


1 answer


This is because it is this

not included in one area. You call it inside a property success

, function callback.

To make it work we need bind

this

.

First, create a constructor method.

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

      



Then add a new method change

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

      

Finally your success

callback

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

      

0


source







All Articles