1

I can't figure out why this code isn't updating state. I call a cloud code method which runs fine and returns the value. You can see this in the console output after the code.

export class Donations extends React.Component {
  constructor() {
    super()

    this.state = {
      totalDonations: 0
    }

    this.getDonations = this.getDonations.bind(this)
  }

  getDonations = () => {
    // Total money donated to Organization for all time
    Parse.Cloud.run('donations', {}).then(function(result) {
      console.log('now need to set state to: ' + result)
      this.setState({ totalDonations: result })
    })
  }

  componentDidMount() {
    // Get data for current Organization (based on User)
    this.getDonations()
  }

  render() {
    const { totalDonations } = this.state
    console.log('this.state.totalDonations: ' + totalDonations)

    return (
      <div></div>
    )
  }
}

export default Donations

Here's what's logged in the console:

(2) this.state.totalDonations: 0
(2) now need to set state to: 4205
David Yeiser
  • 1,438
  • 5
  • 22
  • 33
  • see this: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – bouffelec Sep 20 '18 at 16:39

1 Answers1

1

Use arrow function to retain the this reference. Change then .then callback to (result) => {...}. Like

getDonations = () => {
  // Total money donated to Organization for all time
  Parse.Cloud.run('donations', {}).then( (result) => {
  console.log('now need to set state to: ' + result)
  this.setState({ totalDonations: result })
  })
}

Hope this will help!

Prasun
  • 4,943
  • 2
  • 21
  • 23