PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] When requesting json from google youtube-data-api it never stops sending get requests and exhaust my API per day limit within minutes

 October 13, 2022     axios, javascript, reactjs, youtube-data-api     No comments   

Issue

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>
            )
            )}
        </>
    )
}

enter image description here


Solution

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.



Answered By - JoshD
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing