|
| 1 | +import { usePrivy } from "@privy-io/react-auth"; |
| 2 | +import { toast } from "sonner"; |
| 3 | +import { deleteArtist } from "@/lib/artists/deleteArtist"; |
| 4 | +import { useArtistProvider } from "@/providers/ArtistProvider"; |
| 5 | + |
| 6 | +interface DeleteArtistOptions { |
| 7 | + onSuccess?: () => void; |
| 8 | +} |
| 9 | + |
| 10 | +interface UseDeleteArtistReturn { |
| 11 | + deleteArtist: (artistId: string, options?: DeleteArtistOptions) => Promise<void>; |
| 12 | +} |
| 13 | + |
| 14 | +export default function useDeleteArtist(): UseDeleteArtistReturn { |
| 15 | + const { getAccessToken } = usePrivy(); |
| 16 | + const { artists, setArtists, getArtists } = useArtistProvider(); |
| 17 | + |
| 18 | + const deleteArtistHandler = async ( |
| 19 | + artistId: string, |
| 20 | + options?: DeleteArtistOptions, |
| 21 | + ): Promise<void> => { |
| 22 | + const previousArtists = artists; |
| 23 | + const nextArtists = artists.filter(artist => artist.account_id !== artistId); |
| 24 | + setArtists(nextArtists); |
| 25 | + |
| 26 | + try { |
| 27 | + const accessToken = await getAccessToken(); |
| 28 | + if (!accessToken) { |
| 29 | + throw new Error("Please sign in to delete an artist"); |
| 30 | + } |
| 31 | + |
| 32 | + await deleteArtist(accessToken, artistId); |
| 33 | + options?.onSuccess?.(); |
| 34 | + } catch (error) { |
| 35 | + setArtists(previousArtists); |
| 36 | + toast.error(error instanceof Error ? error.message : "Failed to delete artist"); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + try { |
| 41 | + await getArtists(); |
| 42 | + } catch { |
| 43 | + toast.error("Artist deleted, but failed to refresh the artist list"); |
| 44 | + } |
| 45 | + }; |
| 46 | + |
| 47 | + return { |
| 48 | + deleteArtist: deleteArtistHandler, |
| 49 | + }; |
| 50 | +} |
0 commit comments