0

I'm trying to wait for data in componentDidMount and then change my state isLoading to false but setState is not triggering. I'm able to console.log the data inside branch.init but I don't know why setState is not working.

    state = {
      isLoading: true,
    }

    componentDidMount() {
      console.log("componentDidMount");

      let branchKeyTest = 'key_test_aBcDeF'

      branch.init(branchKeyTest, function(err, data) {
        console.log(JSON.stringify(data, null, 1))

        this.setState({ isLoading: false })

        if (data && data.data_parsed) {
          switch (data.data_parsed.link_type) {
            case 'new_release':
              localStorage.setItem('redirect', JSON.stringify({
                'link_type': 'new_release',
                'release_id': data.data_parsed.release_id
              }));
              break;
            default:
              console.log("do nothing")
          }
        }
      })
    }


  render() {
    const { isLoading } = this.state;
    if (!isLoading) {
      return (
        <div>Done Loading</div>
      )
    else {
      return (
        <div>Still Loading</div>
      )
    } 
  }
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
jj008
  • 1,033
  • 3
  • 23
  • 48

1 Answers1

1

branch.init(branchKeyTest, function(err, data) { needs to be changed to branch.init(branchKeyTest, (err, data) => { because you don't have access to the class's this keyword inside the anonymous function.

The way you wrote it, you don't have access to this because this was referring to the function's context - not the class. By changing it to fat arrow syntax, you can access this for the React class's context.

You can read more about this here.

technogeek1995
  • 3,185
  • 2
  • 31
  • 52