Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Botão Desfazer #2

Open
diegovianagomes opened this issue Sep 13, 2024 · 0 comments
Open

Botão Desfazer #2

diegovianagomes opened this issue Sep 13, 2024 · 0 comments

Comments

@diegovianagomes
Copy link

Adicionei a issue do Botão Desfazer:

No Server

./function/undo-goal-completion-request.ts

`import { eq, gte, lte, and, desc } from 'drizzle-orm'
import { db } from '../db'
import { goalCompletions } from '../db/schema'
import dayjs from 'dayjs'

interface UndoGoalCompletionRequest {
goalId: string
}

export async function undoGoalCompletion({
goalId,
}: UndoGoalCompletionRequest) {
const firstDayOfWeek = dayjs().startOf('week').toDate()
const lastDayOfWeek = dayjs().endOf('week').toDate()

const recentCompletion = await db
    .select()
    .from(goalCompletions)
    .where(
        and(
            eq(goalCompletions.goalId, goalId),
            gte(goalCompletions.createdAt, firstDayOfWeek),
            lte(goalCompletions.createdAt, lastDayOfWeek)
        )
    )
    .orderBy(desc(goalCompletions.createdAt))
    .limit(1)

if (recentCompletion.length === 0) {
    throw new Error('No completion found to undo!')
}

const { id } = recentCompletion[0]

await db.delete(goalCompletions).where(eq(goalCompletions.id, id))

return { status: 'Undo successful' }

}`

./http/routes/undo-completion.ts

`
import { z } from 'zod'
import type { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { undoGoalCompletion } from '../../functions/undo-goal-completion-request'

export const undoCompletionRoute: FastifyPluginAsyncZod = async (
app,
_opts
) => {
app.delete(
'/completions/:goalId',
{
schema: {
params: z.object({
goalId: z.string(),
}),
},
},
async request => {
const { goalId } = request.params

        try {
            await undoGoalCompletion({ goalId })
            return { status: 'Undo successful' }
        } catch (error) {
            if (error instanceof Error) {
                return { status: 'Error', message: error.message }
                // biome-ignore lint/style/noUselessElse: <explanation>
            } else {
                return {
                    status: 'Error',
                    message: 'An unknown error occurred',
                }
            }
        }
    }
)

}
`
E adicionando a rota no server.ts
app.register(undoCompletionRoute)

No Front temos as seguintes funções e chamadas

./componentes/undo-button.tsx

`import { undoGoalCompletion } from '../http/undo-goal-completion'

interface UndoButtonProps {
goalId: string
onUndoSuccess?: () => void
}

export function UndoButton({ goalId, onUndoSuccess }: UndoButtonProps) {
const handleUndo = async () => {
try {
await undoGoalCompletion(goalId)
// Chama a função de callback se fornecida
if (onUndoSuccess) onUndoSuccess()
} catch (error) {
console.error('Error undoing goal completion:', error)
}
}

return (
    // biome-ignore lint/a11y/useButtonType: <explanation>
    <button
        className="text-zinc-400 underline hover:no-underline"
        onClick={handleUndo}
    >
        Desfazer
    </button>
)

}
`

./http/undo-goal-completion.tsx

export async function undoGoalCompletion(goalId: string) { try { const response = await fetch( http://localhost:3333/completions/${goalId}`,
{
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
}
)

    if (!response.ok) {
        throw new Error('Failed to undo goal completion')
    }
} catch (error) {
    console.error('Failed to undo goal completion:', error)
}

}
`

No ./componentes/summary.tsx
Começei adicionando uma "const queryClient = useQueryClient()" dentro da função summary e o botão ficou assim:
`
<UndoButton
goalId={goal.id}
onUndoSuccess={() => {
queryClient.invalidateQueries({
queryKey: ['summary'],
})
queryClient.invalidateQueries({
queryKey: ['pending-goals'],
})
}}
/>

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant