File upload in React-Hook-Form returns empty object upon submission

Viewed 26

I am trying to submit the form using the react-hook form. But it always returns empty data.

The Request payload returns something like this in the browser

{nameOnCurrentLicense: "test Biden", driversLicenseNumber: "dfghj3243546", deliveryAddress: "vbn 456 fghjgfs, UK", driversLicenseNumber: "dfghj3243546", driversLicensePhoto: {0: {}}, driversLicensePricingId: 1, nameOnCurrentLicense: "test Biden", passportPhoto: {0: {}} }

import { data } from 'autoprefixer';
import { useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { Link } from 'react-router-dom';
import { toast } from 'react-toastify';
import {
    Button,
    Container,
    FileInput,
    Input,
    Line,
    Radio,
    TextInput,
    Typography,
} from '../../../../common/components';
import { axiosInstance } from '../../../../config/axiosInstance';
import { createFormData } from '../../../../helpers';
import { useAppDispatch, useAppSelector } from '../../../../hooks';
import {
    useDriverLicenseMutation,
    useDriverLicensePayCardMutation,
    useDriverLicensePayWalletMutation,
} from '../../apis';
import { formTwo } from '../../apis/slice/FormSlice';
import { formProps } from '../../types';
import { DriverLicenseSubmitPayload } from './types';

function Drift() {
    const [price, setPrice] = useState([]);
    const [passportFile, setPassportFile] = useState(null);
    const [licenseFile, setLicenseFile] = useState(null);
    const [driversLicensePricingId, setDriversLicensePricingId] = useState('');
    // api hooks
    const [onDriverLicense, { isLoading }] = useDriverLicenseMutation();
    const [onInitPaymentViaWallet, { isLoading: isInitiatingWallet }] =
        useDriverLicensePayWalletMutation();
    const [onInitPaymentViaCard, { isLoading: isInitiatingCard }] = useDriverLicensePayCardMutation();
    //RHF context
    const priceSelection = useAppSelector((state) => state.formAction.FormTwo);
    const { register, handleSubmit, errors } = useForm({
        defaultValues: {
            nameOnCurrentLicense: data.nameOnCurrentLicense,
            driversLicenseNumber: data.driversLicenseNumber,
            deliveryAddress: data.deliveryAddress,
            passportPhoto: data.passportPhoto,
            driversLicensePricingId: Number(priceSelection.id),
            driversLicensePhoto: data.driversLicensePhoto,
        },
        mode: 'onBlur',
        // resolver: yupResolver(schema),
    });

    //submit handler
    const onSubmitForm = async (data) => {
        try {
            let result = await onDriverLicense({
                nameOnCurrentLicense: data.nameOnCurrentLicense,
                driversLicenseNumber: data.driversLicenseNumber,
                deliveryAddress: data.deliveryAddress,
                passportPhoto: data.passportPhoto,
                driversLicensePricingId: Number(priceSelection.id),
                driversLicensePhoto: data.driversLicensePhoto,
            }).unwrap();
            result.success === true &&
                toast.success(result.message, {
                    position: toast.POSITION.BOTTOM_RIGHT,
                });
        } catch (error) {
            console.log('This is the error', error);
        }
    };

    useEffect(() => {
        axiosInstance
            .get('drivers-license/pricing')
            .then((response) => {
                setPrice(response.data.data);
            })
            .catch((error) => console.log(error));
        return () => {};
    }, []);

    const dispatch = useAppDispatch();
//form field
    const personalInputs = [
        { name: 'nameOnCurrentLicense', type: 'text', label: 'Name on current License' },
        { name: 'driversLicenseNumber', type: 'text', label: "Driver's license number" },
        { name: 'deliveryAddress', type: 'text', label: 'Delivery address' },
    ];

    return (
        <Container containerStyle='py-12'>
            <form onSubmit={handleSubmit(onSubmitForm)}>
                <>
                    <div className='w-full flex md:flex-row flex-col justify-between items-start flex-wrap h-full'>
                        <div className=' w-full md:w-[55%] px-6 py-3'>
                            <Typography textStyle='text-md font-semibold'>Fill out your informations</Typography>
                            <Typography variant='label'>
                                We’ll require you to fill out some information before we get you started.
                            </Typography>

                            <Line variant='header' title='Personal Information' />

                            {personalInputs.map((item, index) => (
                                <TextInput
                                    key={index}
                                    {...register(`${item.name}`)}
                                    id={item.name}
                                    type='text'
                                    label={item.label}
                                    name={item.name}
                                    // error={!!errors.item.name}
                                    // helperText={errors?.field.name?.message}
                                />
                            ))}

                            <Line variant='header' title='Upload Document' />
                            <div className='flex justify-between items-center'>
                                <div className='w-[45%] pt-4'>
                                    <input
                                        {...register('passportPhoto')}
                                        type='file'
                                        name={'passportPhoto'}
                                        accept='image/png, image/gif, image/jpeg'
                                    />
                                </div>
                                <div className='w-[45%] pt-4'>
                                    <input
                                        {...register('driversLicensePhoto')}
                                        type='file'
                                        name={'driversLicensePhoto'}
                                        accept='image/png, image/gif, image/jpeg'
                                    />
                                </div>
                            </div>
                        </div>

                        <div className='w-full md:w-[45%]  pl-0 lg:pl-6 pt-12 md:pt-0'>
                            <Typography variant='h6' textStyle='font-semibold text-center'>
                                Pricing / Years of Validity
                            </Typography>

                            <div className='pt-8'>
                                <Radio
                                    ref={register}
                                    name='driversLicensePricingI'
                                    onChange={(e) => setDriversLicensePricingId(e.target.value)}
                                    data={price}
                                />
                            </div>

                            <div className='w-full bg-GRAY flex justify-between items-center p-8 rounded-xl'>
                                <Typography variant='h5' textStyle='font-semibold'>
                                    Total cost
                                </Typography>
                                {priceSelection.amount !== undefined ? (
                                    <Typography textStyle='text-3xl font-medium text-black'>{`₦ ${priceSelection.amount}`}</Typography>
                                ) : (
                                    <Typography textStyle='text-3xl font-medium text-black'>{`₦ 0.00`}</Typography>
                                )}
                            </div>
                        </div>
                    </div>
                    <div className='w-full md:w-[55%]'>
                        <div className='flex flex-row justify-end items-center w-full pt-16'>
                            <Link to='' className='font-medium text-xs lg:text-sm hover:text-opacity-50'>
                                Cancel
                            </Link>
                            <div className='w-40 ml-4'>
                                <Button
                                    type='submit'
                                    height={'h-10'}
                                    variant='secondary'
                                    containerButton=' w-full px-4 text-black'
                                    text='Buy now'
                                />
                            </div>
                        </div>
                    </div>
                </>
            </form>
        </Container>
    );
}

export default Drift;
0 Answers
Related