Gapi Ошибка при использовании API данных YouTube в приложении reactjs - PullRequest
0 голосов
/ 03 марта 2020

Я создал проект, используя Next. js. Здесь я хотел реализовать функцию с помощью API данных YouTube. Когда пользователь нажимает кнопку youtube connect , открывается всплывающее окно и выполняется аутентификация пользователя. После аутентификации API данных YouTube выдает ответ, содержащий основную c информацию о канале пользователя. Иногда это работало нормально. Но иногда это выдает следующую ошибку:

enter image description here

Вот мой код:

import { Fragment, useEffect, useContext } from "react";
import {gapi} from "../common/api";
import { GOOGLE_CLIENT_ID } from "../../helpers/Constants";
import { AthleteContext } from "../../context/AthleteContextProvider";
import { Button, message } from "antd";
import AthleteProfileService from "../../services/AthleteProfileService";


  const YouTubeConnect = () => {

    const athleteContext = useContext(AthleteContext);
    function authenticate() {
        return gapi.auth2.getAuthInstance()
            .signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
            .then(function() { console.log("Sign-in successful"); },
                  function(err) { console.error("Error signing in", err); });
      }
      function loadClient() {
        gapi.client.setApiKey(GOOGLE_API_KEY);
        return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
            .then(function() { console.log("GAPI client loaded for API");
            execute();
          },
                  function(err) { console.error("Error loading GAPI client for API", err); });
      }
      // Make sure the client is loaded and sign-in is complete before calling this method.
      function execute() {
        return gapi.client.youtube.channels.list({
          "part": "snippet,contentDetails,statistics",
          "mine": true
        })
            .then(function(response) {
                    // Handle the results here (response.result has the parsed body).
                    console.log("Response", JSON.parse(response.body));
                    athleteContext.invokeYoutubeInfo(response.body);
                    AthleteProfileService.connectSocialAccount({
                      attrName: "youtube",
                      attrValue: JSON.parse(response.body).items[0].id
                  }).then(res => {
                      message.success("Youtube profile link added!");
                      athleteContext.setProfileUpdateStatus(true);
                  }).catch(err => {
                      console.log(err);
                      athleteContext.setProfileUpdateStatus(false);
                  })
                  },
                  function(err) { console.error("Execute error", err); });
      }

      function executeFinal() {      
        authenticate().then(() => {
            loadClient();
          })
      }

      gapi.load("client:auth2", function() {
        gapi.auth2.init({client_id: GOOGLE_CLIENT_ID});
          });
      return (
          <Fragment>
               {/* <button onClick={() => authenticate().then(() => loadClient())}>auth</button> */}
               <Button onClick={() => executeFinal()}>Connect</Button>
          </Fragment>
      )
  }
  export default YouTubeConnect;

Я пробовал некоторые решения , Но это все еще показывает ошибку. Пожалуйста, скажите мне, где проблема. Заранее спасибо.

...