Skip to content

Commit

Permalink
refactor: move error & success handling from hook to <DeleteAction/>
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammer5 committed Mar 19, 2024
1 parent 0d008f0 commit f5a1070
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 57 deletions.
15 changes: 14 additions & 1 deletion src/components/sectionList/listActions/DeleteAction.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useAlert } from '@dhis2/app-runtime'
import i18n from '@dhis2/d2-i18n'
import {
Button,
Expand Down Expand Up @@ -86,9 +87,21 @@ function ConfirmationDialog({
onDeleteSuccess()
}

const { show: showDeletionSuccess } = useAlert(
() =>
i18n.t('Successfully deleted {{modelType}} "{{displayName}}"', {
displayName: modelDisplayName,
modelType,
}),
{ success: true }
)

const deleteAndClose = () =>
deleteModel()
.then(onDeleteSuccess)
.then(() => {
showDeletionSuccess()
onDeleteSuccess()
})
// We don't need to do anything on error except for catching it,
// we have all the information on the deleteModelMutation value
.catch(() => null)
Expand Down
62 changes: 6 additions & 56 deletions src/lib/models/useDeleteModelMutation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useDataEngine, useAlert } from '@dhis2/app-runtime'
import i18n from '@dhis2/d2-i18n'
import { useDataEngine } from '@dhis2/app-runtime'
import { useMutation } from 'react-query'
import { Schema } from '../useLoadApp'

Expand All @@ -11,63 +10,14 @@ type MutationFnArgs = {

export function useDeleteModelMutation(schema: Schema) {
const engine = useDataEngine()
const { show: showDeletionSuccess } = useAlert(
({ displayName, modelType }) =>
i18n.t('Successfully deleted {{modelType}} "{{displayName}}"', {
displayName,
modelType,
}),
{ success: true }
)

const { show: showDeletionFailure } = useAlert(
({ displayName, modelType, messages }) => {
if (messages) {
return i18n.t(
'Failed to delete {{modelType}} "{{displayName}}"! {{messages}}',
{ displayName, modelType, messages: messages.join('; ') }
)
}

return i18n.t('Failed to delete {{modelType}} "{{displayName}}"!', {
displayName,
modelType,
})
},
{ success: false }
)

return useMutation({
mutationFn: (variables: MutationFnArgs) => {
const alertPayload = {
modelType: schema.singular,
displayName: variables.displayName,
}

return engine
.mutate({
resource: schema.plural,
id: variables.id,
type: 'delete',
})
.then((result) => {
showDeletionSuccess(alertPayload)
return result
})
.catch((e) => {
if (e?.details?.response?.errorReports) {
showDeletionFailure({
...alertPayload,
messages: e.details.response.errorReports.map(
({ message }: { message: string }) => message
),
})
} else {
showDeletionFailure(alertPayload)
}

throw e
})
return engine.mutate({
resource: schema.plural,
id: variables.id,
type: 'delete',
})
},
})
}

0 comments on commit f5a1070

Please sign in to comment.