How to send file data to server action using next-safe-action & react-hook-form

I’ve created an input and received the file, I can see the data stored in formData, but when I send them to the server-action I receive this error:

Uncaught (in promise) Error: Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.

and the error marks executeCreate, in here:

  `async function onSubmit() {
    if (product) {
      await executeUpdate(form.getValues());
    } else {
      await executeCreate(form.getValues());
    }
    router.refresh(); // could grab a new timestamp from db
    // reset dirty fields
    form.reset(form.getValues());
  }`

and here is it’s definition:

 const {
    executeAsync: executeCreate,
    result: createResult,
    isExecuting: isCreating,
  } = useAction(createProductAction, {
    onSuccess: ({ data }) => {
      toast({
        variant: "default",
        title: "Success! 🎉",
        description: data?.message,
      });
    },
    onError: ({ error }) => {
      toast({
        variant: "destructive",
        title: "Error",
        description: "Error Creating Product",
      });
    },
  });

this approach only is problematic with files and File type, and I want to know if there is a way to use next-safe-action if not I can use the default approach using useEffect to show the result

New contributor

Amin Afshari is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

In my case, I am using the server action for the API call, and I have a separate project for the backend. That’s the reason I am calling the API in the server action. I am using the Next.js safe action for the API call and Zod for validating the form data. However, I haven’t added specific validation for the image because I am sure that the image meets the specified constraints at the time the user uploads it in the ImageUpload component. If the server action is called by an unknown person with bad data, my backend also validates the image, so there will be an error in this case.

I am using the getRandomId function, which provides me with a random ID that I assign to the serverError component. This is because I have a logic to hide an error automatically. When the error hides for the first time and occurs again, React will consider it the same component and keep the default state from the last time. This means it will not render correctly. That’s why I assign a random ID so that on each render, it will consider it a different component because of the key.

HOOKS to manage the state and api call related stuff.

'use client';
import React from 'react';
import { useAction } from 'next-safe-action/hooks';
import { getRandomId } from '@/util';
import toast from 'react-hot-toast';

import {
  deletePropertyImageSafeAction,
  updatePropertyImageSafeAction,
} from '@/server/property-actions';
import { ImageType as InputUploadedImageType } from '@/types';
type ImageType = { file?: File; previewUrl: string; id: string };
function usePropertyImages({
  propertyId,
  previousImages,
  idFromStepsData,
}: {
  propertyId: string | undefined;
  idFromStepsData: string | undefined;
  previousImages: string[] | undefined;
}) {
  const [uploadedImages, setUploadedImages] = React.useState<
    ImageType[]
  >([]);

  const [newlyUploadingImage, setNewlyUploadingImage] =
    React.useState<ImageType | null>(null);

  const {
    execute: updateImageAction,
    reset: resetUpdateImageAction,
    result: updateImageActionResult,
    status: updateImageActionStatus,
  } = useAction(updatePropertyImageSafeAction);
  const { execute: deleteImageAction } = useAction(
    deletePropertyImageSafeAction
  );

  React.useEffect(() => {
    if (updateImageActionResult?.data?.success) {
      return setNewlyUploadingImage(null);
    }
    if (updateImageActionResult.serverError) {
      toast.error(updateImageActionResult.serverError);
      setUploadedImages(preState =>
        preState.filter(image => image.id !== newlyUploadingImage?.id)
      );
      setNewlyUploadingImage(null);
    }
    if (updateImageActionResult?.data?.error) {
      setUploadedImages(preState =>
        preState.filter(image => image.id !== newlyUploadingImage?.id)
      );
      setNewlyUploadingImage(null);
    }
  }, [updateImageActionResult, newlyUploadingImage?.id]);

  React.useEffect(() => {
    const images = previousImages?.map((img: string) => ({
      previewUrl: img,
      id: getRandomId(),
    }));
    setUploadedImages(images || []);
  }, [previousImages]);

  const onRemove = React.useCallback(
    (image: ImageType) => {
      if (propertyId && uploadedImages.length <= 5) {
        return;
      }
      setUploadedImages(preState =>
        preState.filter(
          lastEditedImage => lastEditedImage.id !== image.id
        )
      );
      deleteImageAction({
        deletedImgUrl: image.previewUrl,
        id: (propertyId || idFromStepsData) as string,
      });
    },
    [
      deleteImageAction,
      idFromStepsData,
      propertyId,
      uploadedImages.length,
    ]
  );

  const onFileUpload = React.useCallback(
    (newImage: InputUploadedImageType) => {
      setNewlyUploadingImage(newImage);
      setUploadedImages(preState => [newImage, ...preState]);
      const formData = new FormData();
      formData.append('photo', newImage.file as File);
      formData.append(
        'id',
        (propertyId || idFromStepsData) as string
      );
      updateImageAction(formData);
    },
    [idFromStepsData, propertyId, updateImageAction]
  );
  return {
    uploadedImages,
    resetUpdateImageAction,
    updateImageActionStatus,
    setNewlyUploadingImage,
    updateImageAction,
    newlyUploadingImage,
    setUploadedImages,
    deleteImageAction,
    onRemove,
    updateImageActionResult,
    onFileUpload,
  };
}

export default usePropertyImages;

SEVER action

export const updatePropertyImageSafeAction = action(
  updatePropertyImageSafeActionSchema,
  async body => {
    try {
      const url = new URL(
        `${process.env.BACKEND_BASE}/properties/${body.id}`
      );
      const file = body.photo;
      const formData = new FormData();
      formData.append('photos', file, file.name);

      const res: Response = await fetch(url, {
        method: REQUEST_METHODS.PATCH,
        headers: {
          ...getNodeRequiredRequestHeaders(),
          ...getAuthorizationHeader(),
        },
        body: formData,
      });
      if (!res.ok) {
        const errorResponse = await getApiError(res);
        throw new Error(errorResponse.error);
      }
      revalidateTag(getCacheKey('propertyDetails'));
      return { success: 'Image Uploaded' };
    } catch (err: any) {
      const message = err.message;
      return {
        error: message,
      };
    }
  }
);

Schema

export const updatePropertyImageSafeActionSchema = zfd.formData({
  photo: z.any(),
  id: z.string().nonempty(),
});

Component CODE:

'use client';
import React from 'react';
import { PropertyStepsFormType } from '@/types';
import Bumping from '@/components/ui/Bumping';
import Button from '@/components/ui/Button';
import { UploadPropertyImage } from '@/components/ui/PropertyForm/UploadPropertyImage';
import StepsFormHeader from './StepsFormHeader';

import Show from '@/components/ui/Show';

import ServerError from '@/components/ui/ServerError';
import { getRandomId } from '@/util';
import Text from '@/components/ui/Text';
import usePropertyImages from '@/hooks/usePropertyImages';
import PropertyImagesListPreview from './PropertyImagesListPreviewList';

export default function PropertyImages({
  defaultValues,
  isActive,
  stepsData,
  onNext,
}: PropertyStepsFormType) {
  const {
    newlyUploadingImage,
    onRemove,
    resetUpdateImageAction,
    updateImageActionStatus,
    uploadedImages,
    updateImageActionResult,
    onFileUpload,
  } = usePropertyImages({
    idFromStepsData: stepsData?._id,
    previousImages: defaultValues?.photos,
    propertyId: defaultValues?._id,
  });
  return (
    <Bumping
      as='div'
      isActive={isActive}
      className='max-w-2xl p-10 relative rounded-lg bg-white  mx-auto'
      role='form'
    >
      <StepsFormHeader title='A Picture is Worth a Thousand Words' />
      <UploadPropertyImage
        disabledMessage={
          updateImageActionStatus === 'executing'
            ? 'Please wait while we upload the image...'
            : ''
        }
        onClick={() => {
          resetUpdateImageAction();
        }}
        onFileUpload={onFileUpload}
      />
      <PropertyImagesListPreview
        newlyUploadingImage={newlyUploadingImage}
        onRemove={onRemove}
        propertyId={defaultValues?._id}
        propertyName={
          (defaultValues?.name || stepsData?.name) as string
        }
        uploadedImages={uploadedImages}
      />
      <ServerError
        key={getRandomId()}
        onHide={resetUpdateImageAction}
        error={updateImageActionResult.data?.error}
      />
      <Show when={uploadedImages.length < 5}>
        <Text className='' color='error'>
          Please upload at least 5 images
        </Text>
      </Show>

      <Button
        onClick={() => {
          if (defaultValues) return onNext();
          if (uploadedImages.length < 5) return;
          onNext();
        }}
        type='submit'
        className='w-full rounded-full mt-5'
        size='lg'
        color={uploadedImages.length < 5 ? 'borderedBlack' : 'yellow'}
      >
        {defaultValues ? 'Update' : 'Next'}
      </Button>
    </Bumping>
  );
}

Server Error Component

'use client';
import { cn } from '@/util/cn';
import { motion, AnimatePresence } from 'framer-motion';
import React, { ReactNode, useEffect, useState } from 'react';
import { MdOutlineErrorOutline } from 'react-icons/md';
import { IoMdClose } from 'react-icons/io';
import Show from '@/components/ui/Show';
export default function ServerError({
  error,
  className,
  hideAfterSecond = 5,
  onHide,
}: {
  error?: ReactNode;
  className?: string;
  hideAfterSecond?: number;
  onHide: () => void;
}) {
  const [hide, setHide] = useState(false);
  const [remainingSecond, setRemainingSecond] =
    useState(hideAfterSecond);
  useEffect(() => {
    if (!error) return;
    if (hide || remainingSecond <= 0) return setHide(true);
    const timer = setTimeout(() => {
      setRemainingSecond(preState => preState - 1);
    }, 1000);
    return () => {
      clearTimeout(timer);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [remainingSecond, hide, setHide]);

  useEffect(() => {
    if (!error) return;
    if (hide) onHide();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hide, error]);
  if (!error) return;
  const errorMessage =
    typeof error === 'string' && error.length <= 1
      ? 'Unexpected error from server. Please try again later.'
      : error;

  return (
    <AnimatePresence>
      <Show when={!hide}>
        <motion.div
          key='error'
          className={cn(
            'server-error py-4 px-5 text-lg rounded-xl duration-300 relative my-2 text-black bg-error',
            className
          )}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
        >
          <p className='flex items-center text-charcoal gap-3'>
            <span>
              <MdOutlineErrorOutline size={26} />
            </span>
            <span>{errorMessage}</span>
          </p>
          <IoMdClose
            onClick={() => setHide(true)}
            size={18}
            className='absolute right-0 top-0 mt-3 mr-4 cursor-pointer'
          />
        </motion.div>
      </Show>
    </AnimatePresence>
  );
}

UploadPropertyImage Component

'use client';
import { ImageType } from './EditPropertyImage';
import UploadImage from '@/components/ui/UploadImage';

export const UploadPropertyImage = ({
  onFileUpload,
  disabledMessage,
  onClick,
}: {
  // eslint-disable-next-line no-unused-vars
  onFileUpload: (_: ImageType) => void;
  disabledMessage?: string;
  // eslint-disable-next-line no-unused-vars
  onClick: (event: any) => void;
}) => {
  return (
    <UploadImage
      onFileUpload={onFileUpload}
      disabled={!!disabledMessage}
      onClick={onClick}
      disabledTooltipMessage={disabledMessage}
    />
  );
};

UploadImage Component

'use client';
import React, { ReactNode, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { getRandomId } from '@/util';
import { cn } from '@/util/cn';
import { FiFileText } from 'react-icons/fi';
import { ImageType } from '../PropertyForm/EditPropertyImage';
import ServerError from '@/components/ui/ServerError';
import Show from '@/components/ui/Show';
import Text from '@/components/ui/Text';
import { PROPERTY_IMAGE_MAX_SIZE } from '@/schemas';
import { Tooltip } from '@nextui-org/react';

type Version1 = {
  minWidth?: never;
  minHeight?: never;
  noDimensionLimit?: true;
};
type Version2 = {
  minWidth?: number;
  minHeight?: number;
  noDimensionLimit?: false;
};
type Props = {
  disabled?: boolean;
  maxFileSize?: number;
  // eslint-disable-next-line no-unused-vars
  onFileUpload: (_: ImageType) => void;
  // eslint-disable-next-line no-unused-vars
  onClick?: (event: any) => void;
  field?: any;
  label?: ReactNode;
  size?: 'sm' | 'md' | 'lg';
  wrapperClassName?: string;
  title?: string;
  disabledTooltipMessage?: string;
  minWidth?: number;
  minHeight?: number;
  noDimensionLimit?: boolean;
} & (Version1 | Version2);

export default function UploadImage({
  disabled,
  maxFileSize = PROPERTY_IMAGE_MAX_SIZE,
  onFileUpload,
  disabledTooltipMessage,
  onClick,
  label,
  size = 'md',
  wrapperClassName,
  title = 'Upload photos',
  noDimensionLimit = false,
  minWidth = 1200,
  minHeight = 800,
}: Props) {
  const [fileUploadError, setFileUploadError] = useState('');
  const {
    getRootProps,
    getInputProps,
    isFocused,
    isDragAccept,
    isDragReject,
  } = useDropzone({
    multiple: false,
    accept: {
      'image/png': ['.png', '.jpg', '.jpeg'],
    },
    disabled: disabled,
    maxSize: maxFileSize,
    onDropRejected: issue => {
      if (
        issue?.length &&
        issue[0].errors &&
        issue[0].errors.length &&
        issue[0].errors[0].message
      ) {
        if (issue[0].errors[0].code === 'file-too-large') {
          setFileUploadError('File is larger than 1 MB');
        } else setFileUploadError(issue[0].errors[0].message);
      }
    },
    onDropAccepted: filesData => {
      // Validate image dimensions
      const image = new Image();
      image.src = URL.createObjectURL(filesData[0]);
      image.onload = () => {
        if (
          !noDimensionLimit &&
          (image.width < minWidth || image.height < minHeight)
        ) {
          setFileUploadError(
            `Image must be at least ${minWidth}px wide and ${minHeight}px tall.`
          );
        } else {
          onFileUpload({
            file: filesData[0],
            previewUrl: image.src,
            id: getRandomId(),
          });
        }
      };
    },
  });
  return (
    <Tooltip
      className={cn('max-w-sm', {})}
      classNames={{
        content: 'bg-red-500 text-white',
        base: !disabledTooltipMessage || !disabled ? 'hidden' : '',
      }}
      size='lg'
      color='primary'
      content={disabledTooltipMessage}
    >
      <section className={wrapperClassName} onClick={onClick}>
        <Text
          color='gray'
          className='font-normal mb-1.5 block opacity-80'
          noMargin
          as='label'
          aria-label='upload photo'
          size='sm'
        >
          {label}
        </Text>
        <div
          {...getRootProps({
            className: cn(
              'dropzone border-2  flex flex-col justify-center item-center  border-gray-200 rounded-lg',
              {
                'border-yellow500 border-dashed':
                  isDragAccept || isFocused,
                'border-red-400 border-dashed': isDragReject,
                'p-5': size === 'md',
                'p-2': size === 'sm',
                'p-7': size === 'lg',
              }
            ),
          })}
        >
          {<input {...getInputProps()} />}
          <div className='flex  justify-center flex-col items-center'>
            <FiFileText
              size={size === 'md' ? 44 : size === 'sm' ? 24 : 50}
              className='text-gray-500'
            />
            <p
              className={cn('text-gray-700  font-medium', {
                'text-lg': size === 'md',
                'text-xl': size === 'lg',
                'text-md': size === 'sm',
              })}
            >
              {title}
            </p>
            <p
              className={cn('text-gray-600 ', {
                'text-sm': size === 'md',
                'text-[12px]': size === 'sm',
                'text-md': size === 'lg',
              })}
            >
              drag file formats jpg, png etc
            </p>
          </div>
        </div>
        <aside>
          <Show when={!!fileUploadError}>
            {/* NOTE THIS IS NOT SERVER INSTEAD THIS A CLIENT SIDE ERROR WHILE UPLOADING AN IMAGE */}
            <ServerError
              hideAfterSecond={4}
              key={fileUploadError}
              error={fileUploadError}
              onHide={() => setFileUploadError('')}
            />
          </Show>
        </aside>
      </section>
    </Tooltip>
  );
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật