Hi, I’m a pretty fresh JS dev and can’t figure out what’s wrong with my code. Been trying to fix it for a week. It might me obvious for an experienced developer so I’m asking here.
Dependencies
React.js, react-hook-form, Strapi v4, cloudinary provider for images
What I want to do
I have a form that users can fill out and POST new entries to a collection-type called “establishments”.
Every establishment has some text fields and one media field.
The media field name is img
Here’s a simplified form that uses react-hook-form handleSubmit
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text"/>
<input type="file"/>
<form>
async function onSubmit(data) {
const formData = new FormData();
formData.append(`files.${file.name}}`, data.img);
formData.append("data", JSON.stringify(data));
try {
const response = await fetch(`${BASE_URL}/api/establishments`, {
method: "POST",
body: formData,
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${auth.jwt}`,
},
});
const json = response.json();
console.log(json);
} catch (error) {
console.log(error)
setPublishError(error.toString());
} finally {
setSubmitting(false)
}
}