Stykgwar
Stykgwar

Reputation: 721

Why do I need to refresh my site before the update shows? Tanstack Query/Table

I encountered a problem wherein I need to refresh the website every time i use my useMutation function/button.

Here is the problem, at first, I'm fetching a data from my database using useQuery

  const history = useQuery<GetOverDataReponseType>({
    queryKey: ['data', 'history', from, to],
    queryFn: () => fetch(`/api/data-history? 
    from=${DateToUTCDate(from)}&to=${DateToUTCDate(to)}`).then((res) => res.json())
  })

After this, I fetch the data to my table. I wrapped it on my skeleton wrapper wherein it renders first before it shows.

      <SkeletonWrapper isLoading={history.isFetching}>
        <div className="rounded-md border ">
          <Table>
            <TableHeader>
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id}>
                  {headerGroup.headers.map((header) => {
                    return (
                      <TableHead key={header.id}>
                        {header.isPlaceholder
                          ? null
                          : flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                      </TableHead>
                    )
                  })}
                </TableRow>
              ))}
            </TableHeader>
            <TableBody>
              {table.getRowModel().rows?.length ? (
                table.getRowModel().rows.map((row) => (
                  <TableRow
                    key={row.id}
                    data-state={row.getIsSelected() && "selected"}
                  >
                    {row.getVisibleCells().map((cell) => (
                      <TableCell key={cell.id}>
                        {flexRender(cell.column.columnDef.cell, cell.getContext())}
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={columns.length} className="h-24 text-center">
                    No results.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
        <div className="flex items-center justify-end space-x-2 py-4">
          <Button
            variant="outline"
            size="sm"
            onClick={() => table.previousPage()}
            disabled={!table.getCanPreviousPage()}
          >
            Previous
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
          >
            Next
          </Button>
        </div>
      </SkeletonWrapper>

Now, I have this column wherein I have multiple drop down function wherein it handles functions. I created a approved function wherein it updates to the status to approved as well as pending with same function wherein it changes from approved to pending.

const columns: ColumnDef<OverviewTableRow>[] = [
 ..//other columns
{
 id: "actions",
    cell: ({ row }) => {


      const id = row.original.id
      const router = useRouter()
      const queryClient = useQueryClient();

      const { mutate: approvedButton } = useMutation({
        mutationFn: (id: string) => ApprovedAppointment(id),
        onError: (error) => {
          toast.error('Failed to approve appointment', {
            id: "approved-appointment-error"
          });
        },
        onSuccess: () => {
          toast.success(`Appointment named ${row.original.title} has been approve successfully 🎉`, {
            id: "approved-appointment-success"
          });    
          queryClient.invalidateQueries({ 
            queryKey: ["data", "history"] 
          });
          router.refresh()
        },
    
      });

      const { mutate: pendingButton } = useMutation({
        mutationFn: (id: string) => PendingAppointment(id),
        onError: (error) => {
          toast.error(`Failed to update appointment`, {
            id: "pending-appointment-error"
          });
        },
        onSuccess: () => {
          toast.warning(`Appointment named ${row.original.title} has been moved to pending 🎉`, {
            id: "pending-appointment-success"
          });    
          queryClient.invalidateQueries({ 
            queryKey: ["data", "history"] 
          });
        },
        onSettled: () => {
          router.refresh();
        },
      });
}
]

Dropdown

 <DropdownMenuPortal>
<DropdownMenuSubContent>
<DropdownMenuItem
onClick={() => approvedButton(id)}
                  >
<Check className="mr-2 h-4 w-4 text-emerald-600" />
                    <span>Approved</span>
                  </DropdownMenuItem>
                  <DropdownMenuItem
                   onClick={() => pendingButton(id)}
                  >
                    <CircleDot className="mr-2 h-4 w-4 text-rose-600" />
                    <span>Pending</span>
                  </DropdownMenuItem>
        <DropdownMenuSeparator />
      </DropdownMenuSubContent>
    </DropdownMenuPortal>

Upvotes: 0

Views: 113

Answers (0)

Related Questions