YesPlayMusic/packages/web/hooks/useUserLikedTracksIDs.ts

86 lines
2.7 KiB
TypeScript
Raw Normal View History

2022-05-12 02:45:43 +08:00
import { likeATrack } from '@/web/api/track'
2022-04-05 02:30:07 +08:00
import useUser from './useUser'
2022-05-12 02:45:43 +08:00
import { useMutation, useQueryClient } from 'react-query'
2022-04-16 21:14:03 +08:00
import { IpcChannels } from '@/shared/IpcChannels'
import { APIs } from '@/shared/CacheAPIs'
import { fetchUserLikedTracksIDs } from '../api/user'
2022-04-16 21:14:03 +08:00
import {
FetchUserLikedTracksIDsResponse,
UserApiNames,
} from '@/shared/api/User'
2022-05-12 02:45:43 +08:00
import { useQuery } from 'react-query'
import toast from 'react-hot-toast'
2022-04-05 02:30:07 +08:00
export default function useUserLikedTracksIDs() {
const { data: user } = useUser()
const uid = user?.account?.id ?? 0
return useQuery(
[UserApiNames.FetchUserLikedTracksIds, uid],
2022-04-05 02:30:07 +08:00
() => fetchUserLikedTracksIDs({ uid }),
{
enabled: !!(uid && uid !== 0),
refetchOnWindowFocus: true,
placeholderData: (): FetchUserLikedTracksIDsResponse | undefined =>
2022-04-09 00:28:37 +08:00
window.ipcRenderer?.sendSync(IpcChannels.GetApiCacheSync, {
2022-04-16 21:14:03 +08:00
api: APIs.Likelist,
2022-04-05 02:30:07 +08:00
query: {
uid,
},
}),
}
)
}
export const useMutationLikeATrack = () => {
const queryClient = useQueryClient()
const { data: user } = useUser()
const { data: userLikedSongs } = useUserLikedTracksIDs()
const uid = user?.account?.id ?? 0
const key = [UserApiNames.FetchUserLikedTracksIds, uid]
2022-04-05 02:30:07 +08:00
return useMutation(
2022-04-05 21:23:55 +08:00
async (trackID: number) => {
2022-04-05 02:30:07 +08:00
if (!trackID || userLikedSongs?.ids === undefined) {
throw new Error('trackID is required or userLikedSongs is undefined')
}
2022-04-05 21:23:55 +08:00
const response = await likeATrack({
2022-04-05 02:30:07 +08:00
id: trackID,
like: !userLikedSongs.ids.includes(trackID),
})
2022-04-05 21:23:55 +08:00
if (response.code !== 200) throw new Error((response as any).msg)
return response
2022-04-05 02:30:07 +08:00
},
{
onMutate: async trackID => {
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
await queryClient.cancelQueries(key)
// Snapshot the previous value
const previousData = queryClient.getQueryData(key)
// Optimistically update to the new value
queryClient.setQueryData(key, old => {
const likedSongs = old as FetchUserLikedTracksIDsResponse
const ids = likedSongs.ids
const newIds = ids.includes(trackID)
? ids.filter(id => id !== trackID)
: [...ids, trackID]
return {
...likedSongs,
ids: newIds,
}
})
// Return a context object with the snapshotted value
return { previousData }
},
// If the mutation fails, use the context returned from onMutate to roll back
onError: (err, trackID, context) => {
queryClient.setQueryData(key, (context as any).previousData)
2022-04-05 21:23:55 +08:00
toast((err as any).toString())
2022-04-05 02:30:07 +08:00
},
}
)
}