Skip to content

Commit

Permalink
fix(core): wait for duplicate success before navigating (#5556)
Browse files Browse the repository at this point in the history
  • Loading branch information
ricokahler committed Jan 26, 2024
1 parent 881a991 commit 088830d
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/sanity/src/structure/documentActions/DuplicateAction.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {CopyIcon} from '@sanity/icons'
import {uuid} from '@sanity/uuid'
import React, {useCallback, useState} from 'react'
import {filter, firstValueFrom} from 'rxjs'
import {structureLocaleNamespace} from '../i18n'
import {useRouter} from 'sanity/router'
import {
Expand All @@ -10,6 +11,7 @@ import {
useDocumentOperation,
useCurrentUser,
useTranslation,
useDocumentStore,
} from 'sanity'

const DISABLED_REASON_KEY = {
Expand All @@ -19,6 +21,7 @@ const DISABLED_REASON_KEY = {

/** @internal */
export const DuplicateAction: DocumentActionComponent = ({id, type, onComplete}) => {
const documentStore = useDocumentStore()
const {duplicate} = useDocumentOperation(id, type)
const {navigateIntent} = useRouter()
const [isDuplicating, setDuplicating] = useState(false)
Expand All @@ -32,14 +35,25 @@ export const DuplicateAction: DocumentActionComponent = ({id, type, onComplete})

const currentUser = useCurrentUser()

const handle = useCallback(() => {
const handle = useCallback(async () => {
const dupeId = uuid()

setDuplicating(true)

// set up the listener before executing
const duplicateSuccess = firstValueFrom(
documentStore.pair
.operationEvents(id, type)
.pipe(filter((e) => e.op === 'duplicate' && e.type === 'success')),
)
duplicate.execute(dupeId)

// only navigate to the duplicated document when the operation is successful
await duplicateSuccess
navigateIntent('edit', {id: dupeId, type})

onComplete()
}, [duplicate, navigateIntent, onComplete, type])
}, [documentStore.pair, duplicate, id, navigateIntent, onComplete, type])

if (!isPermissionsLoading && !permissions?.granted) {
return {
Expand Down

0 comments on commit 088830d

Please sign in to comment.