Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading