YgorLourenco
YgorLourenco

Reputation: 15

I dont understand why ".map" is undefined in this variable

This .map object is undefined, but I don't know why. This line "{noticias.map((noticia) => ("

import React from 'react'
import Noticia from './Noticia'
import PropTypes from 'prop-types'

const ListadoNoticias = ({noticias}) =>{

 return (
    <div className='row'>
        {noticias.map((noticia) => (
            <Noticia 
                key={noticia.url}
                noticia={noticia}
            />
        ))}
    </div>
 )
}


ListadoNoticias.propTypes = {
    noticias: PropTypes.array.isRequired
}

export default ListadoNoticias;

The "noticias" variable comes from here

import React, {Fragment, useState, useEffect} from 'react'
import Header from './components/Header'
import Formulario from './components/Formulario'
import ListadoNoticias from './components/ListadoNoticias'

function App() {

  // Definir a categoria e noticia
  const [categoria, guardarCategoria] = useState('') // Esse State guarda a categoria da noticia no hooks
  const [noticias, guardarNoticias] = useState([]) // Vai guadar o array de objetos da requisição em formato JSON

  useEffect(() => {
    const consultarAPI = async () => {
      const API = '81673cba4b934873953af1db871a6ac7'
      const url = `https://newsapi.org/v2/top-headlines?country=br&category=${categoria}&apiKey=${API}`
      const resposta = await fetch(url)
      const noticias = await resposta.json()

      guardarNoticias(noticias.articles)
    }
    consultarAPI()
  }, [categoria]) // Vai usar esse State para mudar as informações da API

  return (
    <Fragment>
      <Header 
        titulo='Buscador de Noticias'
      />
      <div className='container white'>
        <Formulario 
          guardarCategoria={guardarCategoria}
        />
        <ListadoNoticias 
          noticias={noticias}
        />
      </div>
    </Fragment>
  );
}

export default App;

Strangely this code is working on localhost. But when I upload to Netlify, it returns this error on the console. Please look at this image: Error image in Netlify

Upvotes: 1

Views: 353

Answers (1)

Drew Reese
Drew Reese

Reputation: 202686

Issue

The issue here is that fetch is returning an error and your response handling doesn't handle successful failure responses, i.e. valid response that is an error. In this case you are receiving a 426 error status code.

You are likely setting your noticias to an undefined value.

useEffect(() => {
  const consultarAPI = async () => {
    const API = '81673cba4b934873953af1db871a6ac7';
    const url = `https://newsapi.org/v2/top-headlines?country=br&category=${categoria}&apiKey=${API}`;
    const resposta = await fetch(url); // <-- 426 error response
    const noticias = await resposta.json();

    guardarNoticias(noticias.articles); // <-- articles undefined
  }
  consultarAPI();
}, [categoria]);

The undefined noticias state is passed to ListadoNoticias and you attempt to map from it and the error is thrown.

Solution

You should really surround async/await code in a try/catch to handle rejected promises and other various thrown errors. You should also check for a successful fetch.

useEffect(() => {
  const consultarAPI = async () => {
    const API = '81673cba4b934873953af1db871a6ac7';
    const url = `https://newsapi.org/v2/top-headlines?country=br&category=${categoria}&apiKey=${API}`;

    try {
      const resposta = await fetch(url);
      if (!resposta.ok) {
        throw new Error('Network response was not ok');
      }
      const noticias = await resposta.json();
      guardarNoticias(noticias.articles);
    } catch(error) {
      // handle fetch failure or any other thrown errors
    }
  }
  consultarAPI();
}, [categoria]);

Upvotes: 2

Related Questions