Home > Blockchain >  How to display data correctly from an API?
How to display data correctly from an API?

Time:05-25

Hi everyone! I am working on an assignment that loads data from an API and is later displayed on the page. However, I am having trouble displaying the data on the page, especially after the "title" is clicked. These are assignments requirements:

Success Criteria Functionality: Albums load from https://jsonplaceholder.typicode.com/albums and are displayed on the page. -The page displays the title property from the album

-When an album's title is clicked, the album's photos are fetched from https://jsonplaceholder.typicode.com/albums/${albumId}/photos.

-The page displays the title, and the thumbnails of up to 10 of the photos for an album on the page after the album is clicked

Specific Instructions and helpful tips

-The albums have already been fetched in App.js. Write the code to display the albums in App.js and the album details go in AlbumDetail.js.

-The album should display the title Each album should display the photo titles

-Each album should display up to 10 photos but not more An album's photos should only show after the album's title is clicked. The alt attribute for each photo's tag should be set to the photo's title. All information can be displayed on the same page

This is what I have so far:

//App.js//

import React, { useEffect, useState } from "react";
import AlbumDetail from "./AlbumDetail";

function App() {
  const [albums, setAlbums] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/albums?userId=1")
      .then((response) => response.json())
      .then(setAlbums)
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return (
    <div className="App">
    <AlbumDetail albums={albums} />
      </div>
  );
}

export default App;
//AlbumDetail.js//

import React, {useState} from "react";

export default function AlbumDetail({ albums }) {
  const [clicked, setClicked] = useState(false);
  const [photos, setPhotos] = useState([]);
  
  const fetchPhotos = (albumId) => { fetch(`https://jsonplaceholder.typicode.com/albums/${albumId}/photos`)
    .then((response) => response.json())
    .then(setPhotos)
    .catch((error) => {
    console.log(error);
  });                                
  };
  
  const albumsList = photos.map((album, index) => (
  <div key = {index}>
      <h2>{album.title}</h2>
      <p
        onClick ={() => {
          setClicked(true);
          fetchPhotos(album.id);
        }}
        >
      </p>
      </div>
  ));
  
  const postPhotos = (
  <div>
      {photos.map((photos, index) => (
      <p key={index}>{`Photo ${index   1}: ${photo.}`}</p>
      ))}
 </div> 
  );
  
  return (
  <div className="container">
      <div className = "albums">{albumsList}</div>
      <div className="photos">
        <h2> {clicked ? "title for selected album" : "Click the photo of the album"} </h2>
        {clicked && postPhotos}
      </div>
      </div>
  );
}

Thank you for taking the time to read this, I would greatly appreciate any assistance!

CodePudding user response:

Looks like a couple of key problems.

One

const albumsList = photos.map should be const albumsList = albums.map.

Two

const postPhotos = (
  <div>
    {photos.map((photos, index) => {
      <p key={index}>
        {`Photo ${index   1}: ${photo.}`}
      </p>
    })}
  </div> 
);
  1. It should be photos.map((photo not photos.map((photos.

  2. I'm assuming you want to add the image here too. So:

     {photos.map((photo, index) => (
       <figure>
         <figcaption>Photo {index   1}</figcaption>
         <img src={photo.thumbnailUrl} />
       </figure>
     ))}
    

Here's a working example. It may not answer all your issues but at least some images are being displayed.

const { useEffect, useState } = React;

function App() {
  const [albums, setAlbums] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/albums?userId=1")
      .then((response) => response.json())
      .then((data) => {
        setAlbums(data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return (
    <div className="App">
      <AlbumDetail albums={albums} />
    </div>
  );

}

function AlbumDetail({ albums }) {

  const [clicked, setClicked] = useState(false);
  const [photos, setPhotos] = useState([]);
  
  const fetchPhotos = (albumId) => {
    fetch(`https://jsonplaceholder.typicode.com/albums/${albumId}/photos`)
      .then((response) => response.json())
      .then((data) => {
        setPhotos(data);
      })
      .catch((error) => {
        console.log(error);
      });                                
  };
  
  const albumsList = albums.map((album, index) => (
    <div key = {index}>
      <h4>{album.title}</h4>
      <p
        className="link"
        onClick={() => {
          setClicked(true);
          fetchPhotos(album.id);
        }}
      >Get photos
      </p>
    </div>
  ));
  
  const postPhotos = (
    <div>
      {photos.map((photo, index) => (
        <figure>
          <figcaption>Photo {index   1}</figcaption>
          <img src={photo.thumbnailUrl} />
        </figure>
      ))}
   </div> 
  );
  
  return (
    <div className="container">
      <div className = "albums">{albumsList}</div>
      <div className="photos">
        <h2> {clicked ? "title for selected album" : "Click the photo of the album"} </h2>
        {clicked && postPhotos}
      </div>
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('react')
);
.link { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related