본문 바로가기
2024~/React

[타입스크립트] 플레이리스트 추가

by Or0i쿠 2025. 6. 15.

훅 : useCreatePlaylist.ts 

 

spotity_pe/src/hooks/useCreatePlaylist.ts at master · roseraph502on/spotity_pe

Contribute to roseraph502on/spotity_pe development by creating an account on GitHub.

github.com

사용 api

 

Web API Reference | Spotify for Developers

The popularity of the track. The value will be between 0 and 100, with 100 being the most popular. The popularity of a track is a value between 0 and 100, with 100 being the most popular. The popularity is calculated by algorithm and is based, in the most

developer.spotify.com

export const CreatePlaylist = 
async(user_id:string, params: CreatePlaylistRequest)
: Promise<Playlist> => {
 try{
    const {name, playlistPublic ,collaborative, description} = params
        const response = await api.post(`/users/${user_id}/playlists`,{
            name,
            public:playlistPublic,
            collaborative,
            description,
        });
        return response.data;
    }catch(error){
        throw error;
    }
}
import { useMutation, useQueryClient } from "@tanstack/react-query"; // ✨ useMutation과 useQueryClient 훅 임포트
import useGetCrruentUserProfile from "./useGetCurrentUserProfile" // ✨ 현재 사용자 프로필 정보를 가져오는 커스텀 훅 임포트
import { CreatePlaylistRequest } from "../models/playlist"; // ✨ 플레이리스트 생성 요청 데이터 타입 임포트
import { CreatePlaylist } from "../apis/playListApi"; // ✨ 실제 플레이리스트 생성 API 호출 함수 임포트

// ✨ useCreatePlaylist 커스텀 훅 정의
const useCreatePlaylist = () => {
  // ✨ useQueryClient 훅: TanStack Query 캐시를 관리하는 클라이언트 인스턴스를 가져옵니다.
  //    뮤테이션 성공 후 특정 쿼리의 캐시를 무효화하여 데이터를 새로 가져오도록 할 때 사용합니다.
  const queruClient = useQueryClient() // ✨ 오타: queruClient -> queryClient

  // ✨ useGetCrruentUserProfile 훅: 현재 로그인한 사용자 프로필 정보를 가져옵니다.
  //    플레이리스트 생성 API 호출 시 사용자 ID가 필요하므로 이 훅을 사용합니다.
  const {data: user} = useGetCrruentUserProfile();

  // ✨ useMutation 훅: 비동기 작업을 수행하고 그 상태(로딩 중, 성공, 에러 등)를 관리합니다.
  //    주로 데이터 생성, 업데이트, 삭제와 같은 Side Effect를 발생시키는 작업에 사용됩니다.
  return useMutation<
      // ✨ 첫 번째 제네릭: 뮤테이션 성공 시 반환될 데이터 타입 (CreatePlaylist 함수의 반환 타입)
      any, // CreatePlaylist 함수가 Promise<Playlist>를 반환하므로 Playlist 타입이 더 정확할 수 있습니다.
      // ✨ 두 번째 제네릭: 뮤테이션 실패 시 에러 타입
      Error,
      // ✨ 세 번째 제네릭: mutate 함수 호출 시 전달될 인자 타입
      CreatePlaylistRequest
  >({
    // ✨ mutationFn: 실제 비동기 작업을 수행하는 함수입니다.
    //    mutate 함수가 호출될 때 전달된 인자(여기서는 CreatePlaylistRequest 타입의 params)를 받습니다.
    mutationFn : (params: CreatePlaylistRequest) =>{
      // ✨ 사용자 정보(user)가 로드되었는지 확인합니다.
      if(user){
        // ✨ user 정보가 있으면, CreatePlaylist API 함수를 호출합니다.
        //    user.id와 mutate 호출 시 전달받은 params를 인자로 넘깁니다.
        //    이 함수의 반환값(Promise)이 useMutation에 의해 관리됩니다.
        return CreatePlaylist(user.id,params);
      }
      // ✨ user 정보가 없으면, Promise.reject를 사용하여 뮤테이션을 즉시 실패 상태로 만듭니다.
      //    이때 전달된 Error 객체가 useMutation의 error 상태에 저장됩니다.
      return Promise.reject(new Error("user is not defined"));
    },

    // ✨ onSuccess: mutationFn이 성공적으로 완료되었을 때 실행되는 콜백 함수입니다.
    //    mutationFn의 반환값(data)을 인자로 받을 수 있습니다 (여기서는 사용하지 않음).
    onSuccess:()=>{
      // ✨ queryClient.invalidateQueries: 특정 queryKey를 가진 쿼리의 캐시를 무효화합니다.
      //    캐시가 무효화되면 해당 쿼리를 사용하는 컴포넌트는 데이터를 새로 fetching하게 됩니다.
      //    플레이리스트 생성 성공 후, 사용자 플레이리스트 목록 쿼리("current-user-playlists")를 무효화하여
      //    목록이 자동으로 업데이트되도록 합니다.
      queruClient.invalidateQueries({queryKey:["current-user-playlists"]}) // ✨ 오타: queruClient -> queryClient
      console.log("플리 추가 성공");
    },

    // ✨ onError: mutationFn 실행 중 에러가 발생했거나 Promise.reject가 호출되었을 때 실행되는 콜백 함수입니다.
    //    발생한 에러 객체를 인자로 받습니다.
    // onError: (err) => { console.error("플리 추가 실패:", err); } // ✨ onError 콜백은 코드에 정의되어 있지 않지만, useMutation의 옵션으로 제공됩니다.
  });
};

// ✨ useCreatePlaylist 훅을 외부에서 사용할 수 있도록 내보냅니다.
export default useCreatePlaylist;