Next.js Discord

Discord Forum

Can I call form action within a function that is called onClick?

Unanswered
Bengal posted this in #help-forum
Open in Discord
BengalOP
Hi everyone,

Can I call my
"use server";

import { validateRequest } from "@/lib/auth";

export async function getJobById(id: number) {
  const { user } = await validateRequest();

  if (!user) {
    return { error: "Not authenticated" };
  }
  try {
    const response = await fetch(`http://localhost:5000/job?id=${id}`);

    const result = await response.json();

    return result;
  } catch (error) {
    return { error: "Something went wrong!" };
  }
}

From example my download button:
'use client'

  async function handleGetJob(jobId: number) {
    try {
      const bindedGetJobById = getJobById.bind(null, jobId);
      const response = await bindedGetJobById();
      if (response.error) {
        toast({
          description: response.error,
          variant: "destructive",
        });
        return;
      }

      const file = new Blob([response.result], {
        type: "application/json",
      });

      const link = document.createElement("a");
      link.href = URL.createObjectURL(file);
      link.download = response.job_name + ".json";
      link.click();
      URL.revokeObjectURL(link.href);
      link.remove();
    } catch (error) {
      toast({
        description: "Something went wrong",
        variant: "destructive",
      });
    }
  }

  return (
    <DropdownMenuItem
      disabled={!isDownloadable}
      onClick={
        isDownloadable
          ? async () => {
              await handleGetJob(id);
            }
          : undefined
      }
    >
      <DownloadIcon className="mr-2 h-4 w-4" />
      Download
    </DropdownMenuItem>
  );
};

Is it a good practice? Do you have any recommendations?

0 Replies