useDeleteCharacter.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // noinspection JSIgnoredPromiseFromCall
  2. export const useDeleteCharacter = defineMutation(() => {
  3. const queryCache = useQueryCache()
  4. const { mutate, ...mutation } = useMutation({
  5. onMutate(id) {
  6. // save the current character list, and options
  7. const oldCharacterList = queryCache.getQueryData(characterListQuery.key)
  8. // find the index of the deleted character
  9. const characterIndex = _findIndex(oldCharacterList, { id })
  10. let oldOptions, oldCharacter, newCharacterList
  11. if (characterIndex >= 0) {
  12. // save the options and character
  13. oldOptions = queryCache.getQueryData(characterOptionsQuery.key)
  14. oldCharacter = oldCharacterList[characterIndex]
  15. // create a copy of the current character list without the deleted character
  16. const newCharacterList = _reject(oldCharacterList || [], { id })
  17. // calculate new character options
  18. const newOptions = getCharacterOptions(newCharacterList)
  19. // update caches
  20. queryCache.setQueryData(characterListQuery.key, newCharacterList)
  21. queryCache.setQueryData(characterOptionsQuery.key, newOptions)
  22. queryCache.remove({ key: characterByIdQuery(id).key })
  23. // cancel (without refreshing) queries depending on the character
  24. queryCache.cancelQueries({ key: characterListQuery.key })
  25. queryCache.cancelQueries({ key: characterByIdQuery(id).key })
  26. }
  27. // pass the id and the old and new character lists to the other hooks
  28. return { id, oldCharacter, oldCharacterList, newCharacterList, oldOptions }
  29. },
  30. mutation: (id) => useEmit("character:delete", id),
  31. onSettled(_data, _error, _vars, { id }) {
  32. // invalidate the queries to refetch the new data
  33. queryCache.invalidateQueries({ key: characterListQuery.key })
  34. queryCache.invalidateQueries({ key: characterByIdQuery(id).key })
  35. },
  36. onError(err, _vars, { id, oldCharacter, oldCharacterList, oldOptions, newCharacterList }) {
  37. // before applying the rollback, check if the values in the cache are the same
  38. // in case the cache was updated by another mutation or query
  39. if (newCharacterList === queryCache.getQueryData(characterListQuery.key)) {
  40. queryCache.setQueryData(characterListQuery.key, oldCharacterList)
  41. queryCache.setQueryData(characterOptionsQuery.key, oldOptions)
  42. queryCache.setQueryData(characterByIdQuery(id).key, oldCharacter)
  43. }
  44. // handle the error
  45. console.error("[useDeleteCharacter] [onError]", err)
  46. },
  47. onSuccess() {}
  48. })
  49. return {
  50. ...mutation,
  51. deleteCharacter: (id) => mutate(id)
  52. }
  53. })