trying to fetch data using api in react using class based component but don’t know why data are not fetching

Issue

This Content is from Stack Overflow. Question asked by Narayan Dhungel

App.js

 from "react-router-dom";
import React, { Component } from "react";
import News from "./components/News";
export class App extends Component {
  render() {
    return (
      <div>
        
        <News category="sport"/>
      </div>
    );
  }
}

export default App;

unable to fetch data from api showing null in console what is the problem in below code

  async componentDidMount(){
console.log('cdm'); //run after render
let url=`https://newsapi.org/v2/top-headlines?country=us&category=${this.state.category}&apiKey=2149fa5916ca4eae8452f3335ad55084&pageSize=${this.props.pageSize}`;
let data=await fetch(url);
let parsedData = await data.json();
console.log(parsedData);
this.setState({
  articles:parsedData.articles,
  totalResults:parsedData.totalResults
})
  }

when I am not using the category property the data are fetching well but when I am using the category, no data is fetching what is the problem with category?

While not using category

let url=`https://newsapi.org/v2/top-headlines?country=us&apiKey=2149fa5916ca4eae8452f3335ad55084&pageSize=${this.props.pageSize}`;

enter image description here

while using the category

let url=`https://newsapi.org/v2/top-headlines?country=us&category=${this.state.category}&apiKey=2149fa5916ca4eae8452f3335ad55084&pageSize=${this.props.pageSize}`;

enter image description here



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?