| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- // noinspection JSIgnoredPromiseFromCall
- export const useDeleteCharacter = defineMutation(() => {
- const queryCache = useQueryCache()
- // noinspection JSUnusedLocalSymbols
- const { mutate, ...mutation } = useMutation({
- onMutate({ id, optimisticUpdates }) {
- if (optimisticUpdates) {
- // save the current character list, and options
- const oldCharacterList = queryCache.getQueryData(characterListQuery.key)
- // find the index of the deleted character
- const characterIndex = _findIndex(oldCharacterList, { id })
- let oldOptions, oldCharacter, newCharacterList
- if (characterIndex >= 0) {
- // save the options and character
- oldOptions = queryCache.getQueryData(characterOptionsQuery.key)
- oldCharacter = oldCharacterList[characterIndex]
- // create a copy of the current character list without the deleted character
- const newCharacterList = _reject(oldCharacterList || [], { id })
- // calculate new character options
- const newOptions = getCharacterOptions(newCharacterList)
- // update caches
- queryCache.setQueryData(characterListQuery.key, newCharacterList)
- queryCache.setQueryData(characterOptionsQuery.key, newOptions)
- // cancel (without refreshing) queries depending on the character
- queryCache.cancelQueries({ key: characterListQuery.key })
- queryCache.cancelQueries({ key: characterByIdQuery(id).key })
- }
- // pass the id and the old and new character lists to the other hooks
- return { oldCharacter, oldCharacterList, newCharacterList, oldOptions }
- }
- },
- mutation: ({ id, optimisticUpdates = true }) => useEmit("character:delete", id),
- onSettled(_data, _error, { id }) {
- // invalidate the queries to refetch the new data
- queryCache.invalidateQueries({ key: characterListQuery.key })
- queryCache.invalidateQueries({ key: characterByIdQuery(id).key })
- },
- onError(error, { id, optimisticUpdates }, { oldCharacter, oldCharacterList, oldOptions, newCharacterList }) {
- // before applying the rollback, check if the values in the cache are the same
- // in case the cache was updated by another mutation or query
- if (optimisticUpdates && newCharacterList === queryCache.getQueryData(characterListQuery.key)) {
- queryCache.setQueryData(characterListQuery.key, oldCharacterList)
- queryCache.setQueryData(characterOptionsQuery.key, oldOptions)
- queryCache.setQueryData(characterByIdQuery(id).key, oldCharacter)
- }
- // handle the error
- console.error("[useDeleteCharacter] [onError]", error)
- },
- onSuccess() {}
- })
- return {
- ...mutation,
- deleteCharacter: (id) => mutate({ id, optimisticUpdates: true }),
- deleteCharacterFromEvent: (id) => mutate({ id, optimisticUpdates: false })
- }
- })
|