Skip to content

Commit 48d6257

Browse files
committed
bettter delete session
1 parent 00ce80c commit 48d6257

2 files changed

Lines changed: 31 additions & 8 deletions

File tree

client/src/components/session/DeleteSession.tsx

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,25 @@ import { useMutation } from "@tanstack/react-query"
22
import { useTRPC } from "../../lib/trpc"
33
import { Trash } from "@phosphor-icons/react"
44
import ErrorMutation from "../../layout/ErrorMutation"
5-
5+
import { tryCatch } from "../../lib/try-catch"
6+
import { useState } from "react"
67
type Props = {
78
sessionId: string
89
onDelete: () => void
910
}
1011

1112
const 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
}

client/src/lib/try-catch.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}

0 commit comments

Comments
 (0)