I am new in react and wanted to create a YouTube player like app component which stores all the videos of a YouTube playlist and display the playlist in the right side of my desktop (image below), so a friend of mine gave me this code but somethings wrong with it it works fine in the start but after few minutes it exhausts my google API per day limit and wont return anything as you can see the right playlist div block is empty now from the image below.
Please help me figure out why it sends infinite get requests?
*i couldn't get the console screenshot on time but there was a lot of get request errors inside it at the time.
Code Below:
import axios from 'axios';
import React from 'react'
import { useState } from "react";
export default function PlayerItem() {
const [data, setData] = useState([]);
const details = []
async function gettingData() {
await axios.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLu0W_9lII9aiL0kysYlfSOUgY5rNlOhUd&key=[myKey]').then(res => {
setData(res.data.items)
});
}
gettingData();
data.forEach(element => {
details.push(element.snippet.title)
});
// console.log(details);
return (
<>
{details.map((title, index) =>
(
<div className="pl-item" key={index}>
<strong>Video {index + 1}</strong> : {title}.
</div>
)
)}
</>
)
}
import axios from "axios";
//import useEffect from React
import React, { useEffect, useState } from "react";
//Dont need to import these seperately
//import { useState } from "react";
export default function PlayerItem() {
const [data, setData] = useState([]);
const details = [];
async function gettingData() {
await axios
.get(
"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLu0W_9lII9aiL0kysYlfSOUgY5rNlOhUd&key=[myKey]"
)
.then((res) => {
setData(res.data.items);
});
}
//gettingData() ****
//if we put this into a useEffect then we can stop it re-firing on every render
//at the end there is a an array of states / objects that when they are changed they
//useeffect will refire. If we leave this empty then it only fires on the page loading
useEffect(() => {
gettingData();
}, []);
data.forEach((element) => {
details.push(element.snippet.title);
});
// console.log(details);
return (
<>
{details.map((title, index) => (
<div className="pl-item" key={index}>
<strong>Video {index + 1}</strong> : {title}.
</div>
))}
</>
);
}
As someone has already commented, implement useEffect so that it doesn't fire on every re-render (which is caused by setting state). Having an empty dependency array at the end of the useEffect will call it on page load.