Attempting to display four videos in my application by making an API request to YouTube

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

Grabbing my custom hooks

function useFetch(url, defaultResponse) {
    const [data, setData] = useState(defaultResponse);
    async function getDataFromAPI(url) {
        try {
            const res = await fetch(url);
            const data = await res.json();
            setData({
                isLoading: false,
                data
            })
        } catch (e) {
            console.log(e);
        }
    }
    useEffect(() => {
        getDataFromAPI(url);
    }, [url])
    return data;
}

Constructing a personalized hook

export default function YouTubeData() {
    const channelID = "UCXgGY0wkgOzynnHvSEVmE3A";
    const APIKEY = "my-working-key";
    const results = 4
    const apiEndpoint = `https://www.googleapis.com/youtube/v3/search?key=${APIKEY}&channelId=${channelID}&part=snippet,id&order=date&&maxResults=${results}`
    const userFetchResponse = useFetch(apiEndpoint, { isLoading: true, data: null });
    if (!userFetchResponse.data || userFetchResponse.isLoading) {
        return 'Loading...'
    }

Upon logging userFetchResponse.data.items, I receive an array object with various properties

    const {videoId} = (userFetchResponse.data.items.map(obj => "http://www.youtube.com/embed/" + obj.id.videoId));

    return (
        <div>

            {
                videoId.map((link, i) => {
                    var frame =
                        <div key={i} className='youtube'>
                            <iframe
                                title={i}
                                width="560"
                                height="315"
                                src={link}
                                frameBorder="0"
                                allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
                                allowFullScreen>
                            </iframe>
                        </div>
                    return frame
                })
            }
            {this.frame}
        </div>
    )
}

I am facing difficulties creating the variable videoID to store an array of URLs for the jsx src; any assistance?

Answer №1

const {videoId} = (userFetchResponse.data.items.map(obj => "http://www.youtube.com/embed/" + obj.id.videoId));

On the right hand side, an array is created using map, so the left hand side must also be an array.

  const videoId = arr[0]
  // or
  const [videoId] = arr

Avoid using {videoId, as it would assume there is an object on the right hand side.

Answer №2

When you execute

const {item} = someObject

It is equivalent to

const item = someObject.item

In this particular scenario, all you need is to assign an array to a variable, so you can simply use

const imageUrls = response.data.images.map(item => "http://www.example.com/image/" + item.id);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a 403 Forbidden error in Spring Boot while attempting to upload an image to the server via a POST request

Currently, I am facing an issue while trying to upload photos into the database as I keep encountering error 403. Interestingly, everything was functioning smoothly when I tested the endpoint using POSTMAN. However, upon creating the axios request, the err ...

Tips for resolving problems with React builds

Having made some updates to my React application, I attempted to rebuild the changes and redeploy to IIS. Strangely enough, the build process is failing once again. Despite trying everything to resolve this issue, none of my attempts have been successful. ...

Issue with babel-preset-env failing to detect JSX syntax

I'm currently facing an issue while trying to set up a webpack build for the first time. Despite thoroughly reviewing my babel config multiple times in relation to the documentation, I am unable to pinpoint the error causing a problem during the build ...

React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

Necessary Input Field in React Form Does Not Mandate Text Input

I'm having an issue with my subscription dialog form. Even though I have set the email field as required in the code, my form still allows submission with a blank email address. This could potentially cause significant problems for the client. It seem ...

The young one emerges within the SecurePath component temporarily

Setting up authorization in React has been a priority for me. Ensuring that users cannot access unauthorized pages within the application is crucial. To achieve this, I have created a custom component as shown below. import { ReactNode } from "react&q ...

Bypass useEffect Hook in Next.js/React Based on Specific State Update

My latest project involves creating a chart view page that displays sales data. The chart is designed to update via REST API whenever the user modifies dimensions, filter values, or the time period. useEffect(async () => { let [startDate, endDate] = ...

Tips for utilizing two renderCell functions in a datagrid from Material UI without encountering duplication or repetition

Utilizing Material UI, I have designed a table to showcase my data. In this setup, I am required to use renderCell for two specific properties: 'level by user' and 'level by referent'. Issue: The problem arises when Material UI displa ...

Utilizing the same NextJs page layout, showcase varying sets of information

As I work on my Next.js app, I am faced with the challenge of creating two pages that share the same design but present different data. What is the most effective way to achieve this while ensuring that each page has a unique URL path? ...

Utilize ReactJS to link images with posts

How can we modify the action, reducer, and component to include images for each post in the post list? The current action fetches the post list, but we want to also include the images inside each post. Action export const recipesListFetch = (page = 1) =&g ...

What steps do I need to take to modify the MUI Badge component and insert custom text inside?

Is there a way to replace the number with a label next to a new row added to my table using MUI Badge? For example, instead of displaying a number like 4, I want it to show the word "New" as shown in this image: enter image description here This is the co ...

Every time I reload the page, the tab indicator on Material-UI returns to the first tab item

After integrating material-ui tabs with react router, I noticed that the tab indicator resets to the first tab upon page reload. I suspect this is due to the initial value of the tab being set to zero and resetting on page refresh. To visualize the issue, ...

Alert: An invalid value of `false` was received for the non-boolean attribute `className`. To properly write this to the DOM, please provide a string instead: className="false" or use a different

While many have tried to address this issue before, none of their solutions seem to work for me... The error I am encountering is: If you want to write it to the DOM, pass a string instead: className="false" or className={value.toString()}. If ...

Having trouble with the video player not working correctly in Safari when using the video-react package for videos?

Whenever we attempt to set the player start time to any seconds other than 00:00:00, the player actually starts at 00:00:00 and then seeks to the correct seconds after playing for a second or less. This issue is specific to Safari browser and we are curren ...

What is the common approach for organizing an express and react based application - should the server and client code be stored together in one project or kept in separate projects or folders

Coming from a Microsoft background, I have always kept server and client applications in separate projects. Now, I am venturing into writing a client-server application using Express as the backend and React JS as the frontend. As a newbie to these tools, ...

I'm confused as to why redundant data is being transferred over to my URL within a React component

Within my main App.js file, I have implemented the rendering of my Navbar component: import React from 'react'; import { BrowserRouter as Router } from 'react-router-dom'; import Navbar from './components/layout/navbar/Navbar' ...

Struggling with adding space within an input field?

Utilizing Material Ui Data Grid for presentation, with input type inside the data grid. Struggling to insert space between letters and encountering issues with backslash & front slash keys not functioning properly. Must adhere to this syntax as it is use ...

What is the best way to create a compound query in Firebase?

I am working on a TypeScript script to search for a city based on its population... import { getFirebase } from "react-redux-firebase"; ... get fb() { return getFirebase(); } get fs() { return this.fb.firestore(); } getCollection(coll ...

How to disable underlining in Material UI (v1.0 Beta) Input component

Seeking assistance with the Input component in React Material UI library (v1.0 beta), I am endeavoring to eliminate the underline produced by a pseudo element. const styleSheet = createStyleSheet('searchInput', () => ({ underline: { ...