diff --git a/src/actions/CompleteWorkflow.tsx b/src/actions/CompleteWorkflow.tsx index 954a7a3..616bef8 100644 --- a/src/actions/CompleteWorkflow.tsx +++ b/src/actions/CompleteWorkflow.tsx @@ -1,22 +1,44 @@ import {CheckmarkIcon} from '@sanity/icons' +import {ToastContextValue, useToast} from '@sanity/ui' import {useCallback} from 'react' -import {DocumentActionProps, useClient} from 'sanity' +import {DocumentActionProps, SanityClient, useClient} from 'sanity' import {useWorkflowContext} from '../components/WorkflowContext' import {API_VERSION} from '../constants' +export const handleDeleteMetadata = async ( + client: SanityClient, + toast: ToastContextValue, + id: string +) => { + try { + await client.delete(`workflow-metadata.${id}`) + toast.push({ + status: 'success', + title: 'Workflow completed', + }) + } catch (error) { + console.error(error) + toast.push({ + status: 'error', + title: 'Could not complete Workflow', + }) + } +} + export function CompleteWorkflow(props: DocumentActionProps) { const {id} = props const {metadata, loading, error, states} = useWorkflowContext(id) const client = useClient({apiVersion: API_VERSION}) + const toast = useToast() if (error) { console.error(error) } - const handle = useCallback(() => { - client.delete(`workflow-metadata.${id}`) - }, [id, client]) + const handle = useCallback(async () => { + await handleDeleteMetadata(client, toast, id) + }, [client, toast, id]) if (!metadata) { return null @@ -33,8 +55,9 @@ export function CompleteWorkflow(props: DocumentActionProps) { title: isLastState ? `Removes the document from the Workflow process` : `Cannot remove from workflow until in the last state`, - onHandle: () => { - handle() + onHandle: async () => { + await handle() + props.onComplete() }, color: 'positive', } diff --git a/src/components/DocumentCard/CompleteButton.tsx b/src/components/DocumentCard/CompleteButton.tsx index 1fbc0cd..65b6332 100644 --- a/src/components/DocumentCard/CompleteButton.tsx +++ b/src/components/DocumentCard/CompleteButton.tsx @@ -3,6 +3,7 @@ import {Box, Button, Text, Tooltip, useToast} from '@sanity/ui' import React from 'react' import {useClient} from 'sanity' +import {handleDeleteMetadata} from '../../actions/CompleteWorkflow' import {API_VERSION} from '../../constants' type CompleteButtonProps = { @@ -24,20 +25,7 @@ export default function CompleteButton(props: CompleteButtonProps) { return } - client - .delete(`workflow-metadata.${id}`) - .then(() => { - toast.push({ - status: 'success', - title: 'Workflow completed', - }) - }) - .catch(() => { - toast.push({ - status: 'error', - title: 'Could not complete Workflow', - }) - }) + handleDeleteMetadata(client, toast, id) }, [client, toast] )