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)

3
  • Does this answer your question? How to render an array of objects in React? Also read the basics Commented Jul 18, 2022 at 20:53
  • @KonradLinkowski is it any different though with a fetch api? Commented Jul 18, 2022 at 20:57
  • You have already fetched the data and have it in the state. Commented Jul 18, 2022 at 21:01

1 Answer 1

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


Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.