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

React: I can't print the data fetched

As I wrote above, I can’t print the data recovered from the fetch, I’ve been on this for some time without any results.

I’m new to React and learning how to use hooks.

The error I’m getting is:
Cannot read properties of undefined (reading ‘map’)

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

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

export default function App() {
  const [users, setUsers] = useState();
  useEffect(async () => {
    await fetch('https://jsonplaceholder.typicode.com/users/').then(response => response.json()).then(data => setUsers(data))
  }, []);

  return (
    <div>
      {
        users.map((user) => {
          <div>{user.name}</div>
        })
      }
    </div>
  )
}

Can you kindly help me?

>Solution :

  1. Add a default value as empty array to useState to make sure that map() always exist. (The first render will map on an empty array, which is fine since there is not data yet)
    const [users, setUsers] = useState([]);
    
  2. useEffect callback should not be await/async, removed that
  3. You didn’t return anything from your map(), I’ve changed it to:
    {
      users.map((user) => {
        return <div>{user.name}</div>
      })
    }
    

    Or as the short-hand return style:

    {
      users.map(user => <div>{user.name}</div>)
    }
    
const { useState, useEffect } = React;

const App = () => {
  const [users, setUsers] = useState([]);
  useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/users/')
          .then(response => response.json())
          .then(data => setUsers(data))
  }, []);
  
  return (
    <div>
      {
        users.map((user) => {
          return <div>{user.name}</div>
        })
      }
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("react"));
html, body { height: 100vh; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
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