Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
Extract fetched data using map method

I am trying to fetching data from newsapi website. It gives me data as array like object format.

enter image description here

Now, my goal is to iterate this data and display my newsItem component. Here is my code below.

export class News extends Component {
    constructor(){
        super()
        this.state = {
            articles: this.articles
        }
    }
    componentDidMount(){
        fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=d21fe13361b94006b816f98a7c005003`)
        .then(res =>res.json())
        .then(data => this.setState({articles:data.articles}))
    }
  render() {
    return <div className='container my-3'>
        <h1 className='my-3'>NewsDonkey - Top Headlines</h1>
        <div className="row">
                {this.state.articles.map(element=> console.log(element))}
            <div className="col-md-4">
                <NewsItem/>
            </div>
        </div>
    </div>;
  }
}

export default News;

but, browser shows can't read properties of undefined. Here is the error image. enter image description here

Now, you may say that data may be in object format that's why map method is not working. I tried same coding in JS: articles.map(element=> console.log(element)) it extracted data perfectly. Please help me if you find any error in my coding.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The initial value of state.articles is this.articles which is undefined.

At some point in the future, you'll assign a useful value to that property, but until then you can't treat it like the array it will be in the future but isn't yet.

Test the value and do something different.

e.g.

(!this.state.articles && <Loading />}
{this.state.articles && this.state.articles.map(element=> console.log(element))}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda