简体   繁体   中英

I am unable to fetch data from this API. Here is the code

import React, { Component } from 'react'
import NewsItem from './NewsItem';

export class News extends Component {
    constructor() {
        super();
        console.log("News Constructor");
        this.state = {
            articles: this.articles,
            loading: false,
            page: 1,
        }
    }
    async componentDidMount() {
        let url = `https://newsapi.org/v2/top-headlines?country=us&apiKey=########################&page=1&pageSize=20`;
        let data = await fetch(url);
        let parsedData = await data.json();
           console.log(parsedData);
        this.setState({
            articles: this.parsedData.articles,
            totalResults: this.parsedData.totalResults,
        })
    }

    handlePrevClick = async () => {
        console.log("Prev Click");
        let url = `https://newsapi.org/v2/top-headlines?country=us&apiKey=20c171a3b0f845df98a5d436773256d7&page=${this.state.page - 1}&pageSize=20`;
        let data = await fetch(url);
        let parsedData = await data.json();
           console.log(parsedData);
        this.setState({
            articles: this.parsedData.articles,
            page: this.state.page - 1,
        })
    }
    handleNextClick = async () => {
        console.log("Next Click");
        let url = `https://newsapi.org/v2/top-headlines?country=us&apiKey=20c171a3b0f845df98a5d436773256d7&page=${this.state.page + 1}&pageSize=20`;
        let data = await fetch(url);
        let parsedData = await data.json();
        this.setState({
            articles: this.parsedData.articles,
            page: this.state.page + 1,
        })

    }

    render() {
        return (
            <div className="container my-3">
                <h1 className="text-center" >NewsKeeda - Top Headlines</h1>

                <div className="row">
                    {this.state.articles.map((element) => {
                        return <div className="col-md-4" key={element.url} >
                            <NewsItem title={element ? element.title.slice(0, 35) : ""} content={element ? element.content : ""} imageUrl={element.urlToImage} newsUrl={element.url} />
                        </div>

                    })}

                </div>
                <div className="container d-flex justify-content-between">
                    <button disabled={this.state.page <= 1} type="button" onClick={this.handlePrevClick} className="btn btn-dark">&larr; Previous</button>
                    <button disabled={this.state.page + 1 > Math.ceil(this.state.totalResults / 20)} type="button" onClick={this.handleNextClick} className="btn btn-dark">Next &rarr;</button>

                </div>
            </div>
        )
    }
}


export default News;

In the above written code.. I am unable to retrieve data from api. Actually I am able to recieve data from api in json format but unable to pass them to component. Due to security reasons, I replaced my api token with "#################", other than that, everything is the same. I am simply creating a news website using react js and fetching news data from newsapi.org

Welcome to SO, I can see that you are including a body within your url variable. which doesn't appease the fetch function. You also might want to change your api key or edit this and remove it because it's still there in 2 of your url variables.

Here is a good resource for the fetch promise and how to utilize body for POST data: https://developer.mozilla.org/en-US/docs/Web/API/fetch

You can also store your url variable inside the state of the class and refer to it instead of declaring it in each individual function.

this.state = {
articles: this.articles,
loading: false,
page: 1,
url: "apiUrl"
}

There needs to be a ( after return on this line of code for the entire jsx block to be executed:

return ( <div className="col-md-4" key={element.url} >
<NewsItem title={element? element.title.slice(0, 35): ""} content={element? element.content: ""} imageUrl={element.urlToImage} newsUrl={element.url} />
</div>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM