next.jsserver-action

Try to call server action in client component


I'm trying to use the server actions in the client component but it shows error like - TypeError: Cannot read properties of undefined (reading 'workers')

in form.jsx

'use client';

import {uploadFile} from "@/app/lib/File/actions";

<form action={uploadFile(formData)}>
  <TextField label="Title" name={"title"} id={"title"} variant="outlined" fullWidth required />
  <Button type="submit">Submit</Button>
</form>
in action.js

"use server";

export const uploadFile = async (formData) => {
    const title = formData.get('title');
}

Solution

  • You are directly calling the method inside the action callback, instead you should be using a callback so the function does not get called on each render.

    "use client";
    
    import { useCallback } from "react";
    import { uploadFile } from "@/app/lib/File/actions";
    
    export default function MyClientComponent() {
      const onSubmit = useCallback(async (formData) => {
        const result = await uploadFile(formData);
        // do something with result
      }, []);
    
      return (
        <form action={onSubmit}>
          <TextField
            label="Title"
            name={"title"}
            id={"title"}
            variant="outlined"
            fullWidth
            required
          />
          <Button type="submit">Submit</Button>
        </form>
      );
    }
    

    This also allows you to get a result from the uploadFile server action update your UI accordingly.