Home > database >  Simple GET request in React is not working for api call using fetch
Simple GET request in React is not working for api call using fetch

Time:08-17

I am using newsapi to fetch news in React with fetch(url) method but at the end it returns nothing and I am not able to figure out what I am missing, since it does not show any error. My react code to fetch the json data is as below.

import React, { Component } from "react"


class App extends Component{
  constructor(props){
    super(props);
    
    this.state ={
      totalNewsResults : null
    };
  }

  componentDidMount() {
    fetch(url)
        .then(response => response.json())
        .then(data => this.setState({ totalNewsResults: data.totalResults }));
}
  render(){
    const { totalNewsResults } = this.setState;
    return(
      <div>
        Total News results : {totalNewsResults}
      </div>
    );
  }
}

export default App

What this code returns is blank not any error too.

Any help will be appreciated.

Thanks

CodePudding user response:

You're destructuring the method from the this.setState instead of the this.state itself. So it's probably undefined, thus, you don't see anything.


import React, { Component } from "react"


class App extends Component{
  constructor(props){
    super(props);
    
    this.state ={
      totalNewsResults : null
    };
  }

  componentDidMount() {
    fetch(url)
        .then(response => response.json())
        .then(data => this.setState({ totalNewsResults: data.totalResults }));
}
  render(){
    const { totalNewsResults } = this.state;
    return(
      <div>
        Total News results : {totalNewsResults}
      </div>
    );
  }
}

export default App



CodePudding user response:

You are trying to destructure from setState const { totalNewsResults } = this.setState; which should be from state not setState.

Also add a .catch block to produce the error. you can check your network tab also for errors. But I think the main problem in destructuring property.

Also to show then in the DOM use JSON.stringify(totalNewsResults), don't show them directly

  • Related