Making a request to an API using the useEffect hook resulted in an error when attempting to iterate through the list of users. The error message displayed was: TypeError: Cannot read property

import logo from './logo.svg';
import './App.css';
import { useEffect, useState } from 'react';
import User from './components/User/User';

function App() {
  const [user, setUser] = useState([]);
  useEffect(() => {
    // Fetch data from API and set user state
    async function loadData() {
      const response = await fetch("https://randomuser.me/api/?results=10");
      const data = await response.json();
      setUser(data.results);
    }

    loadData()
  }, [])

  console.log(user)

  return (
    

    
    <div className="App">
      <ul>
          {

            user && user.map(usr => <User user={usr}></User>)
          }
      </ul>
     
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

The useEffect hook is used to fetch data from the API and populate the user state. However, when trying to map over the user array, an error occurs indicating that the property 'map' cannot be read of undefined.

Answer №1

It doesn't make sense to use both setUser(data.results) and user.results.map - it's like using data.results.results.map. You should consider using user.map instead, which will also eliminate the need for the user && check since .map can still function with an empty array.

Answer №2

Implement a conditional rendering to display the results only when the API fetch has completed. This is necessary because the user variable remains undefined until the data has been successfully fetched.

Answer №3

It appears that you are fetching an API with Array Name: results. Here is the link: You are setting the user to be data.results. However, when accessing user.results.map, there is an error because there is no 'results' in user. The values of user equal to results.values.

Solution: 1- Change from user.results.map to -> user.map This is how it should look:

import logo from './logo.svg';
import './App.css';
import { useEffect, useState } from 'react';
import User from './components/User/User';

function App() {
  const [user, setUser] = useState([]);
  useEffect(() => {
    // Create a scoped async function in the hook
    async function loadData() {
      const response = await fetch("https://randomuser.me/api/?results=10");
      const data = await response.json();
      setUser(data.results);
    }

    loadData()
  }, [])

  console.log(user)

  return (

  
     
    <div className="App">
      <ul>
          {

            user && user.map(usr => <User user={usr}></User>)
          }
      </ul>
     

Answer №4

Even if you evaluate an empty array as "user &&", it will return true.

Consider using user.length > 0 or isEmpty(user) from lodash/underscore to check for emptiness.

user.length > 0 && user.results && user.results.map(usr => <User user={usr}></User>)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method to change lowercase and underscores to capitalize the letters and add spaces in ES6/React?

What is the best way to transform strings with underscores into spaces and convert them to proper case? CODE const string = sample_orders console.log(string.replace(/_/g, ' ')) Desired Result Sample Orders ...

I am having trouble programmatically setting the 'checked' attribute for a newly added checkbox on an asp.net page

I dynamically added checkboxes using jQuery on my ASPX page and attempted to check some checkboxes by default based on conditions. However, I encountered the following error: Uncaught TypeError: undefined is not a function I tried the following methods ...

Incorporating a Drawer and AppBar using Material-UI and React: Dealing with the error message "Unable to access property 'open' of null."

Currently, I am working on developing an app using React and Material-UI. I have successfully implemented the AppBar component, but I am facing difficulties with setting up the Drawer functionality. The main issue I am encountering is an error message sta ...

Utilizing a router to control a GET request for accessing an image file

Currently utilizing node.js in conjunction with the express framework, I am attempting to initiate a get request for an image by appending it to the body through $('body').append('<img src="images/image.gif?34567">'). Despite rece ...

What can I do to stop my list items from dropping below the menu even when there isn't enough space?

I'm facing an issue with my menu and despite several attempts, I can't seem to resolve it. In Firefox, everything looks fine, but in other browsers, the last anchor tag inside my menu keeps collapsing underneath. I've tried various solutions ...

Using jQuery to create animated effects for hidden input fields

The struggle to smoothly animate and fade in a hidden text field can be witnessed in this example. The goal is to seamlessly move all elements around the text field and button while fading in/out the hidden element. However, it appears that towards the en ...

What causes the express code to generate an error when an empty string is not provided?

I have a basic Express code snippet that calculates the sum of two numbers: const express = require('express') const bodyParser = require('body-parser') const app = express() const port = 3000 app.use(bodyParser.urlencoded({ extended: ...

The category of properties cannot be assigned to the data type 'string'

Within my codebase, there exists a component known as StepperTile. This component has the ability to accept two specific props: title_part_1 title_part_2 However, when attempting to render this component, I encountered an error within the StepperTile fil ...

Differentiate among comparable values through placement regex

I'm currently tackling a challenge involving regex as I work on breaking down shorthand CSS code for the font property. Here is my progress thus far: var style = decl.val.match(/\s*(?:\s*(normal|italic|oblique)){1}/i); style = style ? style ...

The data type 'unknown' cannot be directly converted to a 'number' type in TypeScript

After developing a type for my click handle functions that should return a value with the same type as its parameter, I encountered the following code: type OnClickHandle = <T extends unknown = undefined>(p: T extends infer U ? U : T) => ...

Utilizing Filter in ReactJS to Avoid Displaying Duplicate Entries in an Array

I am facing an issue on my ReactJS page where two dropdown lists are showing duplicate values. These values are retrieved from a json file. I have tried using the filter method to eliminate duplicates, but I am unsure about how to apply it in my array whil ...

Enhance your design with dynamic hover effects

I need assistance with modifying the menu structure generated by Wordpress. Specifically, I want to change the background of #header-nav li ul.children li a when #header-nav li ul.children li ul.children li a:hover is active. Could someone provide guidanc ...

Arrange a collection of objects by two criteria: the end time, followed by the status in accordance with the specified array order if the end times are equal

Is this the best method to arrange data by using infinity? I gave it a try but it doesn't quite meet my requirements. data = [{ "status": "Accepted", "endTime": "" }, { "status": "New", ...

What methods can be used to differentiate between value equality and reference equality when watching something?

In the world of AngularJS, the $watch function comes with an interesting twist - it has an optional third parameter. By default, this parameter is set to false, which means the watch will only trigger if the watched reference changes. But if you set it to ...

What could be causing the oncomplete() method of OmniFaces Ajax utility to fail when triggered by the preRenderView event?

During my preRenderView event, I attempt to use the OmniFaces Ajax utility's oncomplete() method to run some javascript on the client side. However, after testing this feature, I noticed that the javascript is not actually being executed on the client ...

What is the technique for modifying the Bootstrap 4 navbar button icon color?

I am currently working on a Bootstrap website where the hamburger toggler appears when the screen size is less than 992px. The code snippet for this feature is shown below: <button class="navbar-toggler navbar-toggler-right" type=&quo ...

Unable to get response from ajax call using $.post method

I am attempting to retrieve the selected elements' values using jQuery selection. Subsequently, these values are sent to a PHP script via AJAX and then retrieved from the database to be displayed on the same page (referred to as autocomplete). var ma ...

What could be the reason for the failure of the async await implementation in this particular code sample?

While attempting to follow a tutorial on YouTube, I encountered an issue where the code didn't work as expected. Can anyone lend a hand in helping me figure out what might be going wrong? let posts = [ {name: '1', data: 'Hi1'}, ...

Is it possible to retrieve the values of #select1 and #select2 before initiating the AJAX request?

I am presented with the following snippet of HTML code: <select id="choice1"> <option value="0">Option 0</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3 ...

Add a plethora of images to the canvas

Just starting out with Fabric.js and trying to figure out how to draw a picture on the canvas after a drop event. I managed to do it once, but am struggling with inserting more pictures onto the canvas (each new drop event replaces the previous picture). ...