Skip to content

Commit

Permalink
add some default error handlers on uselatitudeaction
Browse files Browse the repository at this point in the history
  • Loading branch information
geclos committed Jul 30, 2024
1 parent 80d709f commit 024443f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 31 deletions.
42 changes: 25 additions & 17 deletions apps/web/src/hooks/useLatitudeAction.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useCallback } from 'react'

import { useToast } from '@latitude-data/web-ui'
import {
inferServerActionError,
inferServerActionReturnData,
Expand All @@ -22,32 +23,39 @@ export default function useLatitudeAction<
onSuccess,
onError,
}: {
onSuccess: (payload: inferServerActionReturnData<TServerAction>) => void
onError: (error: inferServerActionError<TServerAction>) => void
} = { onSuccess: () => {}, onError: () => {} },
onSuccess?: (payload: inferServerActionReturnData<TServerAction>) => void
onError?: (error: inferServerActionError<TServerAction>) => void
} = {},
) {
const { toast } = useToast()

// default callbacks
const successCb = useCallback(onSuccess || (() => {}), [onSuccess])
const errorCb = useCallback(
onError ||
((error: Error) => {
toast({
title: 'Error',
description: error.message,
variant: 'destructive',
})
}),
[onError],
)

const execute = useCallback(
async (data: { [key: string]: unknown }) => {
const [payload, error] = await action(data)
if (error) return errorCb(error)

if (error) {
return onError(error)
}
return onSuccess(payload)
return successCb(payload)
},
[action, onSuccess, onError],
[action, successCb, errorCb],
)

const executeFormAction = useCallback(
async (data: FormData) => {
const [payload, error] = await action(formDataToJson(data))

if (error) {
return onError(error)
}
return onSuccess(payload)
},
[action, onSuccess, onError],
async (data: FormData) => execute(formDataToJson(data)),
[action, execute],
)

return { execute, executeFormAction }
Expand Down
14 changes: 0 additions & 14 deletions apps/web/src/stores/providerApiKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,6 @@ export default function useProviderApiKeys(opts?: SWRConfiguration) {
description: 'API Key ' + apikey.name + ' created',
})
},
onError: (error) => {
toast({
title: 'Error',
description: error.message,
variant: 'destructive',
})
},
})

const { execute: destroy, executeFormAction: destroyFormAction } =
Expand All @@ -55,13 +48,6 @@ export default function useProviderApiKeys(opts?: SWRConfiguration) {
description: 'API Key ' + apikey.name + ' deleted',
})
},
onError: (error) => {
toast({
title: 'Error',
description: error.message,
variant: 'destructive',
})
},
})

return {
Expand Down

0 comments on commit 024443f

Please sign in to comment.