skip to Main Content

I’m encountering a problem while using the YouTube API to fetch data in my React application. Although the data is successfully fetched, it doesn’t seem to be stored in the useState variable as expected. Consequently, my VideoCard component, which relies on this data, isn’t being called. How can I troubleshoot this issue and ensure that the fetched data is properly stored in the state variable?

import React, { useEffect, useState } from "react";
import { YOUTUBE_VIDEOS_API } from "../utils/constants";
import VideoCard from "./VideoCards";

const VideoContainer = () => {
  const [videos, setVideos] = useState([]);

  useEffect(() => {
    getVideos();
  }, []);

  const getVideos = async () => {
    try {
      const data = await fetch(YOUTUBE_VIDEOS_API);
      const json = await data.json();

      setVideos([...videos, ...json?.items]);
      console.log(json);
    } catch (e) {
      console.error(e);
    }
  };

  return (
    <div className="m-4 flex flex-wrap">
      {videos.map((card, index) => {
        <VideoCard key={index} card={card} />;
      })}
    </div>
  );
};

export default VideoContainer;

Outputjson: {"kind": "youtube#videoListResponse",

etag: "fQlUo5S4JJ9QA_SUhvAXezB2SHI",

items: [{…..},{…..},{…..},],

nextPageToken: "CAUQAA",

}

2

Answers


  1. I think you need to use return keyword here :

    <div className="m-4 flex flex-wrap">
      {videos.map((card, index) => {
        return <VideoCard key={index} card={card} />;
      })}
    </div>
    
    Login or Signup to reply.
  2. You probably wanted to use implicit return

       <div className="m-4 flex flex-wrap">
          {videos.map((card, index) => <VideoCard key={index} card={card} />)}
        </div>
    

    Or just add return keyword

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search