prmdpsn56
prmdpsn56

Reputation: 9

Showing all the results of news api in react

I'm new to React and I am fetching data using the news API and I want to display all the results but I am not sure how to do it. I have only been able to display one results using the following code:

 if (country && data.cod !== '404')
 {
        const noa = data.totalResults
        console.log("the value is",noa)
        this.setState({
          Author: data.articles[0].author,
          Title: data.articles[0].title,
          Description: data.articles[0].description,
          Imageurl: data.articles[0].urlToImage,
          Publishedat: data.articles[0].publishedAt,
          Content: data.articles[0].content,
          error: ''
       })
 } 

 render() { 
    return (
      <div className='wrapper'>
         <Form getWeather={this.getWeather}>
            <Data
                Author={this.state.Author}
                Title={this.state.Title}
                Description={this.state.Description}
                Imageurl={this.state.Imageurl}
                Publishedat={this.state.Publishedat}
                Content={this.state.Content}
                error={this.state.error}
              />
          </Form>
       </div>
    );
  }
}

Upvotes: 0

Views: 425

Answers (1)

Funk Soul Ninja
Funk Soul Ninja

Reputation: 2193

If the news API response has multiple items in an array, you will need to reshape your state object like so:

state = { articles: [] } // default state

You would then use setState to update the articles array with the response object like so:

this.setState({ articles: data.articles })

In your render function, rather than displaying only one <Data /> component, render multiple by mapping over this.state.articles like so:

render() {
  return (
    <div className='wrapper'>
      <Form getWeather={this.getWeather} />
      {this.state.articles.map(article => (
        <Data
          key={/*use something unique like article id here*/}
          Author={article.author}
          Title={article.title}
          Description={article.description}
          Imageurl={article.urlToImage}
          Publishedat={article.publishedAt}
          Content={article.content}
        />
      ))}
    </div>
  )
}

This should do it.

Upvotes: 1

Related Questions