0

I am trying to fetch data from https://randomuser.me/api/ using react useEffect hook. Instead of the data to be displayed, I get an error, "Error: Objects are not valid as a React child (found: object with keys {number, name}). If you meant to render a collection of children, use an array instead". I logged the results on my console, I realised the problem is from some of the nested objects, which outputs [object Object]. However, I don't know why some other nested objects display correctly. Below is my code:

import { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import '../../App.css';

const UsersList = () => {

  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch("https://randomuser.me/api/")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result.results);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <div>
        {items.map((item, id) => (
        <div className="card content-panel" key={id}>
          
          <img src={item.picture.medium} alt="Profile pic" className="avatar-user-list" />

          <div className="card-text">
            <p>
              {item.name.first} &nbsp; {item.name.last}
            </p>
            <p>{item.location.street}</p>
            <p>{item.email}</p>
          </div>

          <div className="arrow-bg">
            <span className="arrow">&#x2192;</span>
          </div>        
        </div>
        ))}
      </div>
    );
  }
}

export default UsersList;
1
  • Can you put an example of the api response ? Maybe the problem is the {item.location.street}, it's possible that it is an object with number and name properties Commented Jan 13, 2021 at 23:27

1 Answer 1

1

item.location.street is an object.

According to the response API, this is the street object.

"street": {
   "number": 4850,
   "name": "Rue Dumenge"
},

Instead of rendering

<p>{item.location.street}</p>

You should render something like

<p>{`${item.location?.street?.number} ${item.location?.street?.name}`}</p>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.