0

Having done the necessary to read the data using fetchAPI, I am having problems displaying the content because of the nature of the array.

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

function Home() {
  const [userData, setUserData] = useState([]);

  async function getData() {
    let response = await fetch("https://api.xxxxxxxx.io/something/students");
    let data = await response.json();
    return data;
  }

  //call getData function
  getData().then((data) => console.log(data)); //
  useEffect(() => {
    getData()
      .then((data) => {
        setUserData(data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return (
    <div>
      {Object.keys(userData).map((item, index) => (
        <div key={index}>{item}</div>
      ))}
    </div>
  );
}

export default Home;

When I checked the console, the data are displayed but it is only showing students with no other data displayed. I have the data below.

enter image description here

8
  • Well, Object.keys(userData) will give you back ["students"]. If you want to display all student objects then do userData.students.map(student => ...) and access the student properties you want to show. Commented Oct 7, 2020 at 17:52
  • Why not just remove the dependency array from useEffect? for the Promise resolution? A useEffect without a dependency runs every rerender anyway. Also, you can userData.students.map(({email}) => <p>{email}</p>) Edit: Remove the dependency array because, you are calling the getData function outside useEffect also right. Commented Oct 7, 2020 at 17:54
  • Note that this has nothing to do with React: it's a question about normal JS. But on a React note: stop generating divs in divs. Even though you're using JSX, the result is still going to be HTML, and semantic markup is important. Put that mapping inside a Fragment, not a <div> at the very least. Commented Oct 7, 2020 at 17:56
  • @FelixKling it is complaining... "Cannot read property 'map' of undefined" Commented Oct 7, 2020 at 18:01
  • Probably because your data initially doesn't have a students property. Maybe you want setUserData(data.students); and userData.map(...) instead. Commented Oct 7, 2020 at 18:05

1 Answer 1

1

Try the following changes:

const [userData, setUserData] = useState({ students: [] });

...

return (
    <div>
      {userData.students.map((item, index) => (
        <div key={index}>{item}</div>
      ))}
    </div>
  );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Please, how do I use accordion in react

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.