Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
Cannot read properties of undefined (reading 'map') with REST response

I'm novice in React and have problem with map. My react component

const NewsComponent = () => {
const params = useParams()
const pk = params.pk
const [news, setNews] = useState([])

useEffect(() =>{
    const getNews = async() => {
        await httpClient.get(`/feed/${pk}`)
            .then((response) => {
                setNews(response.data);
            })
    }
    getNews();
}, [])

return(
    <div>
        {news.results.map((post, index) =>(
            <div>
                <h1>{post}</h1>
            </div>
        ))}
    </div>
)
}

My response from backend:

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "title": "asdasd",
            "text": "asdasdasd",
            "likes": [],
            "dislikes": [],
            "attachments": []
        }
    ]
}

But it doesn't work.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

news state on as initial value as array and you need to use it as an object.

const [news, setNews] = useState({})

Also, in the html you need to check if results is not undefined.

{news.results?.map((post, index) =>(
        <div>
            <h1>{post}</h1>
        </div>
    ))}
about 4 years ago · Juan Pablo Isaza Denunciar

0

There are several issues with your code

The first one is the API response!

It's an object, not an array, but you left the initial value of the state as an empty array.

const [news, setNews] = useState({});

The second thing is that there is no data in the initial rendering, so there is no result in the news state, that's why it gives you an error. To solve this, you can use optional chaining.

{news.results?.map((post, index) =>(
    <div>
        <h1>{post}</h1>
    </div>
))}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda