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

208
Visualizações
Error on the map function: Cannot read properties of undefined (reading 'map') in react js

I know this question has been asked again, but I'm not sure what I'm doing wrong because no solution is working for me. my code:

import React, { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((json) => {
        setItems(json.items);
      })

      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <p>Data is loading...</p>;
  }
  return (
    <div className="App">
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            name: {item.name} | email: {item.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

I tried to write it liek this too, to check if the array exists and i dont get and error but I dont get anything as a result :

{items?.map((item) => (
          <li key={item.id}>
            name: {item.name} | email: {item.email}
          </li>
        ))}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Change useState to this: const [loading, setLoading] = useState(true); On first load App function return before useEffect undefined code.

If it still does not work add question mark before accesing prop. Like this:

<ul>
     {items?.map((item) => (
        <li key={item?.id}>
            name: {item?.name} | email: {item?.email}
         </li>
     ))}
</ul>

Adding question mark makes it optional.

about 4 years ago · Juan Pablo Isaza Relatório

0

you need to convert first the response to json and then set to state.

fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json()).then((data) => {
        setItems(data);
      })

From documentation, fetch does not directly return the JSON response body but instead returns a promise that resolves with a Response object. The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.

about 4 years ago · Juan Pablo Isaza Relatório

0

Hello looking at the jsonplaceholders documentation you need to first transform the response with json() when fetching like this

  useEffect(() => {
    setLoading(true);
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => { 
        return response.json() // return response.json() first
      })
      .then((json) => { 
        setItems(json) // then set the json into the items
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

Without the converting it to json first the you set the response object instead of the json array

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