File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -2,24 +2,25 @@ import { useMutation } from "@tanstack/react-query"
22import { useTRPC } from "../../lib/trpc"
33import { Trash } from "@phosphor-icons/react"
44import ErrorMutation from "../../layout/ErrorMutation"
5-
5+ import { tryCatch } from "../../lib/try-catch"
6+ import { useState } from "react"
67type Props = {
78 sessionId : string
89 onDelete : ( ) => void
910}
1011
1112const DeleteSession = ( props : Props ) => {
1213 const trpc = useTRPC ( )
14+ const [ error , setError ] = useState < string | null > ( null )
1315 const mutation = useMutation ( trpc . deleteSession . mutationOptions ( ) )
1416
1517 const deleteSession = async ( ) => {
16- try {
17- await mutation . mutateAsync ( {
18- sessionId : props . sessionId ,
19- } )
18+ const result = await tryCatch ( mutation . mutateAsync ( { sessionId : props . sessionId } ) )
19+ if ( result . error ) {
20+ setError ( result . error . message )
21+ }
22+ if ( result . data ) {
2023 props . onDelete ( )
21- } catch ( error ) {
22- console . log ( error )
2324 }
2425 }
2526
@@ -33,7 +34,7 @@ const DeleteSession = (props: Props) => {
3334 >
3435 < Trash className = "mr-2" /> Delete
3536 </ button >
36- { mutation . error && < ErrorMutation data = { mutation . error } / >}
37+ { error && < p className = "text-red-600" > { error } </ p > }
3738 </ div >
3839 )
3940}
Original file line number Diff line number Diff line change 1+ // Types for the result object with discriminated union
2+ type Success < T > = {
3+ data : T
4+ error : null
5+ }
6+
7+ type Failure < E > = {
8+ data : null
9+ error : E
10+ }
11+
12+ type Result < T , E = Error > = Success < T > | Failure < E >
13+
14+ // Main wrapper function
15+ export async function tryCatch < T , E = Error > ( promise : Promise < T > ) : Promise < Result < T , E > > {
16+ try {
17+ const data = await promise
18+ return { data, error : null }
19+ } catch ( error ) {
20+ return { data : null , error : error as E }
21+ }
22+ }
You can’t perform that action at this time.
0 commit comments