The formData object is always empty, so it’s not saving anything

I want to use the useForm along with a validation system to save data using the append() function and send it to MongoDB with a fetch request. However, when I inspect the formData object, it appears empty, and I receive a ‘no files uploaded’ error when I POST with fetch.

ManageRestaurantForm.jsx

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React from 'react'
import { FormProvider, useForm } from 'react-hook-form'
// PAGES
import DetailsSection from './DetailsSection'
import CuisinesSection from './CuisinesSection'
import MenuSection from './MenuSection'
import ImageSection from './ImageSection'
import { forumFill } from '../../fetch/Fetch'
const ManageRestaurantForm = () => {
const formMethods = useForm();
const { handleSubmit } = formMethods;
const onSubmit = handleSubmit(async (formDataJson) => {
try {
const formData = new FormData();
formData.append("restaurantName", formDataJson.restaurantName);
formData.append("city", formDataJson.city);
formData.append("country", formDataJson.country);
formData.append(
"deliveryPrice",
(formDataJson.deliveryPrice * 100).toString());
formData.append(
"estimatedDeliveryTime",
formDataJson.estimatedDeliveryTime.toString());
formData.append("cuisines", formDataJson.cuisines)
formDataJson.menuItems.forEach((menuItem, index) => {
formData.append(`menuItems[${index}][name]`, menuItem.name);
formData.append(
`menuItems[${index}][price]`,
(menuItem.price * 100).toString()
);
});
console.log(formDataJson.menuItems)
formDataJson.menuItems.forEach((menuItem, index) => {
formData.append(`menuItems[${index}][name]`, menuItem.name);
formData.append(
`menuItems[${index}][price]`,
(menuItem.price * 100).toString()
);
});
if (formDataJson.imageFiles && formDataJson.imageFiles.length > 0) {
Array.from(formDataJson.imageFiles).forEach((file, index) => {
formData.append(`imageFiles[${index}]`, file);
});
}
console.log(formData)
await forumFill("http://localhost:7000/api/my/restaurant", formData);
} catch (err) {
console.log(err)
}
})
return (
<div>
<FormProvider {...formMethods}>
<form onSubmit={onSubmit}>
{/* FORM COMPONENTS */}
<DetailsSection />
<CuisinesSection/>
<MenuSection />
<ImageSection />
<span className='flex justify-end'>
<button type="submit" className='bg-red-600 text-white h-full mb-10 w-40 rounded hover:rounded-md hover:duration-300 duration-300 p-2 font-bold hover:bg-red-500 cursor-pointer text-2xl'>
Save
</button>
</span>
</form>
</FormProvider>
</div>
)
}
export default ManageRestaurantForm
</code>
<code>import React from 'react' import { FormProvider, useForm } from 'react-hook-form' // PAGES import DetailsSection from './DetailsSection' import CuisinesSection from './CuisinesSection' import MenuSection from './MenuSection' import ImageSection from './ImageSection' import { forumFill } from '../../fetch/Fetch' const ManageRestaurantForm = () => { const formMethods = useForm(); const { handleSubmit } = formMethods; const onSubmit = handleSubmit(async (formDataJson) => { try { const formData = new FormData(); formData.append("restaurantName", formDataJson.restaurantName); formData.append("city", formDataJson.city); formData.append("country", formDataJson.country); formData.append( "deliveryPrice", (formDataJson.deliveryPrice * 100).toString()); formData.append( "estimatedDeliveryTime", formDataJson.estimatedDeliveryTime.toString()); formData.append("cuisines", formDataJson.cuisines) formDataJson.menuItems.forEach((menuItem, index) => { formData.append(`menuItems[${index}][name]`, menuItem.name); formData.append( `menuItems[${index}][price]`, (menuItem.price * 100).toString() ); }); console.log(formDataJson.menuItems) formDataJson.menuItems.forEach((menuItem, index) => { formData.append(`menuItems[${index}][name]`, menuItem.name); formData.append( `menuItems[${index}][price]`, (menuItem.price * 100).toString() ); }); if (formDataJson.imageFiles && formDataJson.imageFiles.length > 0) { Array.from(formDataJson.imageFiles).forEach((file, index) => { formData.append(`imageFiles[${index}]`, file); }); } console.log(formData) await forumFill("http://localhost:7000/api/my/restaurant", formData); } catch (err) { console.log(err) } }) return ( <div> <FormProvider {...formMethods}> <form onSubmit={onSubmit}> {/* FORM COMPONENTS */} <DetailsSection /> <CuisinesSection/> <MenuSection /> <ImageSection /> <span className='flex justify-end'> <button type="submit" className='bg-red-600 text-white h-full mb-10 w-40 rounded hover:rounded-md hover:duration-300 duration-300 p-2 font-bold hover:bg-red-500 cursor-pointer text-2xl'> Save </button> </span> </form> </FormProvider> </div> ) } export default ManageRestaurantForm </code>
import React from 'react'
import { FormProvider, useForm } from 'react-hook-form'


// PAGES
import DetailsSection from './DetailsSection'
import CuisinesSection from './CuisinesSection'
import MenuSection from './MenuSection'
import ImageSection from './ImageSection'
import { forumFill } from '../../fetch/Fetch'


const ManageRestaurantForm = () => {

  const formMethods = useForm(); 
    const { handleSubmit } = formMethods; 

    
    const onSubmit = handleSubmit(async (formDataJson) => {
      try {
          
          const formData = new FormData();

          formData.append("restaurantName", formDataJson.restaurantName);
          formData.append("city", formDataJson.city);
          formData.append("country", formDataJson.country);
      
          formData.append(
            "deliveryPrice",
            (formDataJson.deliveryPrice * 100).toString());

          formData.append(
            "estimatedDeliveryTime",
            formDataJson.estimatedDeliveryTime.toString());
          
          formData.append("cuisines", formDataJson.cuisines)

          formDataJson.menuItems.forEach((menuItem, index) => {
            formData.append(`menuItems[${index}][name]`, menuItem.name);
            formData.append(
              `menuItems[${index}][price]`,
              (menuItem.price * 100).toString()
            );
          });

        console.log(formDataJson.menuItems)
       formDataJson.menuItems.forEach((menuItem, index) => {
        formData.append(`menuItems[${index}][name]`, menuItem.name);
        formData.append(
          `menuItems[${index}][price]`,
          (menuItem.price * 100).toString()
        );
      });

      if (formDataJson.imageFiles && formDataJson.imageFiles.length > 0) {
        Array.from(formDataJson.imageFiles).forEach((file, index) => {
          formData.append(`imageFiles[${index}]`, file);
        });
      }
      
      console.log(formData)
        await forumFill("http://localhost:7000/api/my/restaurant", formData);

        } catch (err) {
          console.log(err)
          
        }
    })


  return (
    <div>
      <FormProvider {...formMethods}>
            <form onSubmit={onSubmit}>

            {/* FORM COMPONENTS */}

          <DetailsSection />
          <CuisinesSection/>
          <MenuSection />
          <ImageSection />


            <span className='flex justify-end'>
                      <button type="submit" className='bg-red-600  text-white h-full mb-10 w-40 rounded hover:rounded-md hover:duration-300 duration-300 p-2 font-bold hover:bg-red-500 cursor-pointer text-2xl'>
                          Save
                     </button>
            </span>
            </form>
      </FormProvider>
    </div>
  )
}

export default ManageRestaurantForm

Above, the formFill function is come from:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// forms/manage-restaurant
export const forumFill = async (url, data) => {
try {
const formDataJSON = JSON.stringify(data);
const rawResponse = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: formDataJSON
});
const content = await rawResponse.json();
console.log(formDataJSON)
console.log(content);
} catch (error) {
console.log(error)
}
};
</code>
<code>// forms/manage-restaurant export const forumFill = async (url, data) => { try { const formDataJSON = JSON.stringify(data); const rawResponse = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: formDataJSON }); const content = await rawResponse.json(); console.log(formDataJSON) console.log(content); } catch (error) { console.log(error) } }; </code>
// forms/manage-restaurant
export const forumFill = async (url, data) => {

    try {
      const formDataJSON = JSON.stringify(data); 
    const rawResponse = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: formDataJSON 
    });
      const content = await rawResponse.json();
  
    console.log(formDataJSON)
    console.log(content);
    } catch (error) {
      console.log(error)
    } 
  
  };

Backend of this jsx file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const cloudinary = require("cloudinary").v2;
const mongoose = require("mongoose");
const { Restaurant } = require("../mongodb/models/restaurant");
class Controller {
async createMyRestaurant(req, res) {
try {
if (!req.file || req.file.length === 0) {
return res.status(400).json({ message: "No files uploaded" });
}
const existingRestaurant = await Restaurant.findOne({ user: req.userId });
if (existingRestaurant) {
return res.status(409).json({ message: "User restaurant already exists" });
}
const imageFile = req.File;
console.log(`Your imageFile is ${imageFile}`)
const b64 = Buffer.from(imageFile.buffer).toString("base64");
const dataURI = "data:" + imageFile.mimetype + ";base64," + b64;
const uploadResponse = await cloudinary.uploader.upload(dataURI);
const imageUrl = uploadResponse.url;
console.log(`Your imageUrl is ${imageUrl}`)
const restaurant = new Restaurant({
body: req.body,
lastUpdate: new Date(),
});
await restaurant.save();
res.status(201).send(restaurant);
} catch (err) {
console.log(err);
res.status(500).json({ message: "Something went wrong :(" });
}
}
}
module.exports = Controller;
</code>
<code>const cloudinary = require("cloudinary").v2; const mongoose = require("mongoose"); const { Restaurant } = require("../mongodb/models/restaurant"); class Controller { async createMyRestaurant(req, res) { try { if (!req.file || req.file.length === 0) { return res.status(400).json({ message: "No files uploaded" }); } const existingRestaurant = await Restaurant.findOne({ user: req.userId }); if (existingRestaurant) { return res.status(409).json({ message: "User restaurant already exists" }); } const imageFile = req.File; console.log(`Your imageFile is ${imageFile}`) const b64 = Buffer.from(imageFile.buffer).toString("base64"); const dataURI = "data:" + imageFile.mimetype + ";base64," + b64; const uploadResponse = await cloudinary.uploader.upload(dataURI); const imageUrl = uploadResponse.url; console.log(`Your imageUrl is ${imageUrl}`) const restaurant = new Restaurant({ body: req.body, lastUpdate: new Date(), }); await restaurant.save(); res.status(201).send(restaurant); } catch (err) { console.log(err); res.status(500).json({ message: "Something went wrong :(" }); } } } module.exports = Controller; </code>
const cloudinary = require("cloudinary").v2;
const mongoose = require("mongoose");
const { Restaurant } = require("../mongodb/models/restaurant");

class Controller {
    async createMyRestaurant(req, res) {
        try {

            if (!req.file || req.file.length === 0) {
                return res.status(400).json({ message: "No files uploaded" });
            }

            const existingRestaurant = await Restaurant.findOne({ user: req.userId });

            if (existingRestaurant) {
                return res.status(409).json({ message: "User restaurant already exists" });
            }

            const imageFile = req.File;
            
            console.log(`Your imageFile is ${imageFile}`)

            const b64 = Buffer.from(imageFile.buffer).toString("base64");
            const dataURI = "data:" + imageFile.mimetype + ";base64," + b64;
            const uploadResponse = await cloudinary.uploader.upload(dataURI);
            const imageUrl = uploadResponse.url;

            console.log(`Your imageUrl is ${imageUrl}`)

            const restaurant = new Restaurant({
                body: req.body,
                lastUpdate: new Date(),
            });

            await restaurant.save();

            res.status(201).send(restaurant);
        } catch (err) {
            console.log(err);
            res.status(500).json({ message: "Something went wrong :(" });
        }
    }
}

module.exports = Controller;

Project: githubLink

The expected result was, with the help of useForm creating an object appropriately and POST it into my mongoDB tablet but the error that I face is that formData was empty and unable to send anything.

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