0

I'm trying to do a simple fetch through the componentDidMount lifecycle method. However, the result does not appear on the page as it should unless I have a one second timeout. I've gathered it's due to the async nature of the fetch, but how can I fix that without having to use setTimeout? Would componentDidUpdate work/how would you use it?

      constructor(props) {
        super(props);
        this.state = { value: '' };
        this.getValue= this.getValue.bind(this);
      }

        getValue() {
            return (
                fetch(url, {
                    method: 'GET',
                }).then(response => {
                    if (response.status >= 400) {
                        throw new Error('no response: throw');
                    }
                    return response.json()
                }).then(response => {
                    this.setState({value: response});
                }).catch((error) => {
                    this.setState({
                        value: 'no response: catch'
                    })
                })
            );
        }


    componentDidMount(){
        //this.getValue(); //does not work
        setTimeout(() => this.getValue(), 1000); //this works & populates page
    }


    render() {
            return (
                  <div>
                     <div>{this.state.value}</div>
                  </div>
            )
    }
user7674254
  • 87
  • 1
  • 3
  • 15

1 Answers1

0

Be sure you are binding your this.getValue method to the proper context in the constructor. When you put it in your setTimeout, you have it in a fat arrow function which binds to this implicitly.

constructor(props) {
  super(props);
  this.getValue = this.getValue.bind(this);
}

getValue() { ... }

componentDidMount() {
  this.getValue();
}
Danny Delott
  • 6,756
  • 3
  • 33
  • 57
  • it's normal method calling, binding is not required.. :) – Mayank Shukla Jul 19 '17 at 17:48
  • 1
    What do you mean? `this.setState` requires `this` being bound to the component instance. His code snippet does not show where this is happening, and as it is written he's calling it from the context of `fetch`. – Danny Delott Jul 19 '17 at 17:52
  • check this answer you will understand when and why binding is required. [**Link**](https://stackoverflow.com/a/41391426/5185595) :) – Mayank Shukla Jul 19 '17 at 17:56