Next.js Discord

Discord Forum

Forwarding File object from client component state to server action

Unanswered
style posted this in #help-forum
Open in Discord
Hey how do i do that? I tried stringifiying the values from formdata but unfortunatelly it's not working for File obj.

cliuent
const handleSubmit = async (e: FormEvent) => {
        e.preventDefault()

        const form = e.target as HTMLFormElement
        const formData = new FormData(form)

        const values: { [key: string]: string | number | boolean | string[] | File[] } = {}

        formData.forEach((value, key) => {
            values[key] = value as any;
        })

        values['amenities'] = amenities.map((amenity) => amenity.value)

        values['images'] = images

        const data = await uploadImageAndCreateProperty(JSON.stringify(values), user)
    }

2 Replies

action
export async function uploadImageAndCreateProperty(values: string, user: User) {
    const { images, name, description, bedroomCount, bathroomCount, areaSizeInM2, priceInUSD, amenities, forSale, city, country, address, state, zipCode } = JSON.parse(values) as FormData;

    const userProfile = await deductBalance(user, 5);
    if (!userProfile) {
        console.error('Failed to deduct balance');
        return;
    }

    const slug = `${name.replace(/\s+/g, '-').toLowerCase()}-${Date.now()}`;

    const imagesUrl = [];
    for (const image of images) {
        console.log('Uploading image:', image.name)
        const { data: uploadData, error: uploadError } = await supabase.storage
            .from('properties-images')
            .upload(`images/${slug}/${image.name}`, image, {
                cacheControl: '3600',
                upsert: false
            });

        if (uploadError) {
            console.error('Error uploading image:', uploadError);
            return;
        }

        const imageUrl = await getPublicUrl(uploadData.path);
        imagesUrl.push(imageUrl);
    }

    const locationId = await getOrCreateLocation(city, country, address, state, zipCode);
    console.log(locationId)

    const { data, error } = await supabase
        .from('properties')
        .insert([{
            name,
            description,
            images: imagesUrl,
            bedroomCount: parseInt(bedroomCount),
            bathroomCount: parseInt(bathroomCount),
            areaSizeInM2: parseFloat(areaSizeInM2),
            priceInUSD: parseFloat(priceInUSD),
            amenities,
            forSale: forSale === 'on' ? true : false,
            slug,
            published: false,
            location: locationId,
            user_id: user.id
        }]);

    if (error) {
        console.error('Error inserting data:', error);
        return;
    }

    console.log('Property inserted:', data);
    return data;
}