◾️ usage example 1
import React, { useEffect, useState } from "react";
import { youtubeApi } from "../apis/apis";
const Main = () => {
const [state, setState] = useContext([]]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const fetchData = async () => {
youtubeApi
.popularVideo()
.then((res) => {
const {
data: { items },
} = res;
setState(items);
})
.catch((err) => {
setError("fetch data error");
})
.finally(() => {
setLoading(false);
});
};
useEffect(() => {
fetchData();
}, []);
.....
◾️ usage example 2
import React, { useEffect, useState } from "react";
import { youtubeApi } from "../apis/apis";
const Main = () => {
const [state, setState] = useContext([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const fetchData = async () => {
try {
const {
data: { items },
} = await youtubeApi.popularVideo();
setState(items);
} catch {
setError("fetch data error");
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
.....
◾️ api sample
import axios from "axios";
const api = axios.create({
baseURL: "https://www.googleapis.com/youtube/v3/",
params: {
key: process.env.REACT_APP_API_KEY,
},
});
const commonParams = {
part: "snippet",
maxResults: 30,
regionCode: "JP",
type: "video",
};
export const youtubeApi = {
popularVideo: () =>
api.get("videos", {
params: {
...commonParams,
chart: "mostPopular",
},
})
};