#Forwarding File object from client component state to server action

3 messages · Page 1 of 1 (latest)

warped wharf
#

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)
    }

#

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;
}
hasty valleyBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)