본문 바로가기

React

[React] youtube api (2)이용참고

https://developers.google.com/youtube/v3/docs/search/list?hl=en&apix_params=%7B%22part%22%3A%5B%22snippet%22%5D%2C%22maxResults%22%3A30%2C%22q%22%3A%22css3%22%2C%22regionCode%22%3A%22kr%22%2C%22type%22%3A%5B%22video%22%5D%7D 

 

Search: list  |  YouTube Data API  |  Google Developers

Search: list API 요청에 지정된 쿼리 매개변수와 일치하는 검색결과의 모음을 반환합니다. 기본적으로 검색결과의 집합은 쿼리 매개변수와 일치하는 video, channel, playlist 리소스를 식별하지만, 특정

developers.google.com

part:snippet

maxresult: 30

q:css3

regionCode:kr

type:video

선택 후 execute >showCode

해서 나온

GET https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=30&q=css3&regionCode=kr&type=video&key=[YOUR_API_KEY] HTTP/1.1

에서 css3을 수정

 

GET https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=30&q=${imput}&regionCode=kr&type=video&key=[YOUR_API_KEY] HTTP/1.1

 

ex 코드 / 참고 :  {input}없으면 검색창에 검색후  구글 콘솔 검사에서 #result...이런값이 안뜸  

import React from "react";
import "./index.css";
import { useRef, useEffect } from "react";
import { useDispatch } from "react-redux";
import { getVideoList } from "../../../store/video/videoSlice";

const SearchForm = () => {
  const dispatch = useDispatch();
  const inputRef = useRef();
  const onSearch = (input) => {
    const url = ` https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=30&q${input}&regionCode=kr&type=video&key=키값`;

    dispatch(getVideoList(url));
  };
  const onSubmit = (e) => {
    e.preventDefault();
    const input = inputRef.current.value;
    input && onSearch(input);
    inputRef.current.value = "";
  };
  return (
    <form className="search" onSubmit={onSubmit}>
      <input
        placeholder="검색"
        type="text"
        className="searchInput"
        ref={inputRef}
      />
      <button className="searchBtn">
        <img
          src="/images/search.png"
          alt="search icon"
          className="searchIcon"
        />
      </button>
    </form>
  );
};

export default SearchForm;

▲ 위 코드를 이용해 작성한 것에서 사이트 검색누르면 콘솔검사에 값이 들어가게 바뀐걸 확인할 수 있음.

 

 

import axios from "axios";
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

export const getVideoList = createAsyncThunk("GET_VIDEO_LIST", async (url) => {
  try {
    const res = await axios.get(url);
    return res.data.items;
  } catch (err) {
    console.log(err);
  }
});

const videoSlice = createSlice({
  name: "video",
  initialState: {
    data: [],
  },
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getVideoList.fulfilled, (state, action) => {
      console.log("액션페이로드", action.payload);
      state.data = action.payload;
    });
  },
});

export default videoSlice.reducer;

... 작성