Skip to content

Commit

Permalink
feat(playground): redirect on afterPersistError
Browse files Browse the repository at this point in the history
  • Loading branch information
matej21 committed Jun 6, 2024
1 parent 5e27d87 commit e9d4629
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions packages/playground/admin/lib/components/binding/persist.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { PersistTrigger, SugaredRelativeSingleField, useField } from '@contember/interface'
import { PersistTrigger, SugaredRelativeSingleField, useCurrentRequest, useField } from '@contember/interface'
import { Button } from '../ui/button'
import { Loader } from '../ui/loader'
import { ReactElement, ReactNode, useCallback, useEffect } from 'react'
import { ReactElement, ReactNode, useCallback, useEffect, useRef, useState } from 'react'
import { ToastContent, useShowToast } from '../ui/toast'
import { ErrorPersistResult, SuccessfulPersistResult } from '@contember/binding'
import { Slot } from '@radix-ui/react-slot'
import { useErrorFormatter } from '../errors'
import { usePersist } from '@contember/react-binding'
import { dict } from '../../../lib/dict'
import { useRedirect } from '@contember/react-routing'

export const FeedbackTrigger = (props: { children: ReactElement }) => {
return <Slot {...props} {...usePersistFeedbackHandlers()} />
Expand Down Expand Up @@ -57,6 +58,14 @@ export const usePersistErrorHandler = () => {

export const usePersistSuccessHandler = () => {
const showToast = useShowToast()
const redirect = useRedirect()
const [initialRequest] = useState(useCurrentRequest())
const [forceRedirect, setForceRedirect] = useState(false)
useEffect(() => {
if (forceRedirect) {
redirect(it => !it || it !== initialRequest ? it : { ...it })
}
}, [forceRedirect, initialRequest, redirect])

return useCallback((result: SuccessfulPersistResult) => {
showToast(
Expand All @@ -66,12 +75,8 @@ export const usePersistSuccessHandler = () => {
type: 'success',
})
if (result.type === 'justSuccess' && result.afterPersistError) {
showToast(
<ToastContent
title={dict.persist.afterPersistError}
/>, {
type: 'warning',
})
// deliberately redirecting in useEffect so custom redirects have a priority
setForceRedirect(true)
}
}, [showToast])
}
Expand Down

0 comments on commit e9d4629

Please sign in to comment.