skip to Main Content

Here in my component I have onSubmit which every time a task is added, it must reload the page, but it is not reloading after the onSubmit function is called, I have already checked and I do not receive errors in the console, even the toast is sent, but the refresh () is not done

"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation"
import React, { useRef, ReactNode } from "react"
import { useForm } from "react-hook-form"
import { upsertKanbanTaskSchema } from "../schema"
import { upsertKanbanTask } from "./actions"
import { toast } from "@/components/ui/use-toast"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select"
import { z } from "zod"
import { Task } from "../types"

type KanbanUpsertSheetProps = {
  children?: React.ReactNode
  defaultValue?: Task
}

export function KanbanAddSheet({ children }: KanbanUpsertSheetProps) {

  const ref = useRef<HTMLDivElement>(null)
  const router = useRouter()

  const form = useForm({
    resolver: zodResolver(upsertKanbanTaskSchema)
  })
  const onSubmit = form.handleSubmit(async (data) => {
    await upsertKanbanTask(data)
    router.refresh()

    ref.current?.click()
    toast({
      title: 'Sucesso!',
      description: 'Sua tarefa foi adicionada com sucesso.',
    })
  })
  return (
    <Sheet>
      <SheetTrigger asChild>
        <div ref={ref}>{children}</div>
      </SheetTrigger>
      <SheetContent>
        <Form {...form}>
          <form onSubmit={onSubmit} className="space-y-8 h-screen">
            <SheetHeader>
              <SheetTitle>Adicionar Tarefas</SheetTitle>
              <SheetDescription>
                Preencha os campos abaixo para adicionar uma nova tarefa.
              </SheetDescription>
            </SheetHeader>
            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Título</FormLabel>
                  <FormControl>
                    <Input placeholder="exemplo: Trabalho" {...field} />
                  </FormControl>
                  <FormDescription>
                    Esse é o título da sua tarefa.
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Descrição</FormLabel>
                  <FormControl>
                    <Input placeholder="exemplo: Enviar Emails para Cliente" {...field} />
                  </FormControl>
                  <FormDescription>
                    Esse é a descrição da sua tarefa.
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Status</FormLabel>
                  <FormControl>
                    <Select {...field}>
                      <SelectTrigger className="w-full">
                        <SelectValue placeholder="Selecione um Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectGroup>
                          <SelectLabel>Status</SelectLabel>
                          <SelectItem value="a-fazer">A Fazer</SelectItem>
                          <SelectItem value="fazendo">Fazendo</SelectItem>
                          <SelectItem value="feito">Feito</SelectItem>
                        </SelectGroup>
                      </SelectContent>
                    </Select>
                  </FormControl>
                </FormItem>
              )}
            />
            <SheetFooter className="mt-auto">
              <Button type="submit">Adicionar Tarefa</Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}

I’ve tried to force the refresh in several ways, but to no avail.

const onSubmit = form.handleSubmit(async (data) => {
    await upsertKanbanTask(data)
    
    // force update
    router.push(router.asPath)

    ref.current?.click()
    toast({
        title: 'Sucesso!',
        description: 'Sua tarefa foi adicionada com sucesso.',
    })
})

2

Answers


  1. If router.refresh() isn’t working, you can try using window.location.reload() to force a full page reload. This method will refresh the entire page and might be more reliable if router.refresh() isn’t behaving as expected.

    const onSubmit = form.handleSubmit(async (data) => {
      await upsertKanbanTask(data)
    
      // Force page reload
      window.location.reload()
    
      ref.current?.click()
      toast({
        title: 'Sucesso!',
        description: 'Sua tarefa foi adicionada com sucesso.',
      })
    })
    
    Login or Signup to reply.
  2. It seems like you’re using next/navigation’s useRouter and trying to refresh the page after submitting a form.
    first, Check if the upsertKanbanTask function is working correctly. this code snippet should help

    "use client"
    
    import { zodResolver } from "@hookform/resolvers/zod"
    import { useRouter } from "next/navigation"
    import React, { useRef, ReactNode } from "react"
    import { useForm } from "react-hook-form"
    import { upsertKanbanTaskSchema } from "../schema"
    import { upsertKanbanTask } from "./actions"
    import { toast } from "@/components/ui/use-toast"
    import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
    import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
    import { Input } from "@/components/ui/input"
    import { Button } from "@/components/ui/button"
    import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select"
    import { z } from "zod"
    import { Task } from "../types"
    
    type KanbanUpsertSheetProps = {
      children?: React.ReactNode
      defaultValue?: Task
    }
    
    export function KanbanAddSheet({ children }: KanbanUpsertSheetProps) {
      const ref = useRef<HTMLDivElement>(null)
      const router = useRouter()
    
      const form = useForm({
        resolver: zodResolver(upsertKanbanTaskSchema)
      })
    
      const onSubmit = form.handleSubmit(async (data) => {
        try {
          await upsertKanbanTask(data)
          // Try refreshing the page with router.refresh
          router.refresh()
          // Alternatively, force update with router.push
          // router.push(router.asPath)
          // As a last resort, force a full page reload
          // window.location.reload()
          toast({
            title: 'Sucesso!',
            description: 'Sua tarefa foi adicionada com sucesso.',
          })
        } catch (error) {
          console.error("Failed to upsert task:", error)
          toast({
            title: 'Erro!',
            description: 'Não foi possível adicionar a tarefa.',
            variant: 'destructive'
          })
        } finally {
          ref.current?.click()
        }
      })
    
      return (
        <Sheet>
          <SheetTrigger asChild>
            <div ref={ref}>{children}</div>
          </SheetTrigger>
          <SheetContent>
            <Form {...form}>
              <form onSubmit={onSubmit} className="space-y-8 h-screen">
                <SheetHeader>
                  <SheetTitle>Adicionar Tarefas</SheetTitle>
                  <SheetDescription>
                    Preencha os campos abaixo para adicionar uma nova tarefa.
                  </SheetDescription>
                </SheetHeader>
                <FormField
                  control={form.control}
                  name="title"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Título</FormLabel>
                      <FormControl>
                        <Input placeholder="exemplo: Trabalho" {...field} />
                      </FormControl>
                      <FormDescription>
                        Esse é o título da sua tarefa.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Descrição</FormLabel>
                      <FormControl>
                        <Input placeholder="exemplo: Enviar Emails para Cliente" {...field} />
                      </FormControl>
                      <FormDescription>
                        Esse é a descrição da sua tarefa.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="status"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Status</FormLabel>
                      <FormControl>
                        <Select {...field}>
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder="Selecione um Status" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectGroup>
                              <SelectLabel>Status</SelectLabel>
                              <SelectItem value="a-fazer">A Fazer</SelectItem>
                              <SelectItem value="fazendo">Fazendo</SelectItem>
                              <SelectItem value="feito">Feito</SelectItem>
                            </SelectGroup>
                          </SelectContent>
                        </Select>
                      </FormControl>
                    </FormItem>
                  )}
                />
                <SheetFooter className="mt-auto">
                  <Button type="submit">Adicionar Tarefa</Button>
                </SheetFooter>
              </form>
            </Form>
          </SheetContent>
        </Sheet>
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search