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

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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