1

I am trying to get API to render the json data into a react so I will be able to view the cards and the info of the members. I am able to get it to console log but I am unsure what to do next to render the info as visible into the actual .

After adding to the code from the comment below, I changed my code to this and the error I'm now getting is: Line 11:6: Parsing error: Identifier 'Card' has already been declared. (11:6)

ttsssss
  • 95
  • 1
  • 2
  • 12
  • Does this answer your question? [How to render an array of objects in React?](https://stackoverflow.com/questions/41374572/how-to-render-an-array-of-objects-in-react) Also read the [basics](https://reactjs.org/docs/lists-and-keys.html#gatsby-focus-wrapper) – Konrad Jul 18 '22 at 20:53
  • @KonradLinkowski is it any different though with a fetch api? – ttsssss Jul 18 '22 at 20:57
  • You have already fetched the data and have it in the state. – Konrad Jul 18 '22 at 21:01

1 Answers1

1

After fetching the data and getting the json response, you can start by putting the result in your state and dynamically render a card for each user.

Here's some starter code for your desired behaviour

import React, { useEffect, useState } from "react";

const Card = (props) => {
  const { user } = props;

  return <div>
    <div>{user.gender}</div>
    <div>{user.name.title} {user.name.first} {user.name.last}</div>
    <hr />
  </div>;
};

export default function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const url = "https://randomuser.me/api/?results=5";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        const {results} = json;
        // Only put the results in state, ie, the actual users array
        setUsers(results);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      {users.map((user) => (
        <Card key={user.email} user={user} />
      ))}
    </div>
  );
}


Moath
  • 540
  • 2
  • 9
  • I changed my code in the original question to add what you said. I'm now getting a Line 11:6: Parsing error: Identifier 'Card' has already been declared. (11:6) error. Could you consult further? – ttsssss Jul 18 '22 at 22:25
  • As the error says, the Card component has already been declared. I created a simple Card component, when you copy the snippet remove the import line to use the simple card. This is just to demo the use case. – Moath Jul 19 '22 at 08:22