I am uploading products into database. I have a submit function:
const onSubmit = async (e) => {
e.preventDefault()
try {
await uploadImage()
//this executes at the same time as the above function
window.location.reload()
} catch (error) {
alert(error)
}
}
Everything under uploadImage doesn't wait for it to finish
this uploadImage function takes the image and uploads it to cloudinary like this:
const uploadImage = async () => {
const data = new FormData()
if (formImage) {
data.append("file", formImage)
data.append("upload_preset", "***-")
data.append("cloud_name", "***")
try {
const resp = await fetch("***", {
method: "post",
body: data
})
const dataJson = await resp.json()
setUrl(dataJson.secure_url);
//I had insertProduct Function under the other one on submit but they executed at the same time so it didn't work
insertProduct(producto, dataJson.secure_url)
} catch(error) {
console.log(error)
}
}
}
I have these two functions inside the same file.
↓↓↓↓ This is my inserProduct function ↓↓↓↓
Now this insertProduct function I have it in a .js file outside /pages
import { collection, query, where, addDoc, getDoc, getDocs } from "firebase/firestore";
import { db } from "../config/firebase";
export const insertProduct = async (prodData, image) => {
const {
nombre, precioOferta, precioRegular,
cantStock, sku,
breveDescripcion, visible,
envioGratis, coincideMedidas,
descripcion, picture,
etiquetas, vendor,
available_colors, available_sizes
} = prodData
const tags = etiquetas.split(" ")
if (image) {
try {
const uploadedProduct = await addDoc(collection(db, "products"), {
name: nombre,
price: precioOferta,
regular_price: precioRegular,
vendor: {
vendor_id: vendor.vendor_id
},
sku,
freeShipping: envioGratis,
stock_quantity: cantStock,
is_published: visible,
short_description: breveDescripcion,
description: descripcion,
picture: image,
tags,
available_sizes,
available_colors
})
return uploadedProduct
} catch (error) {
console.log(error)
}
}else{
console.log('no hay imagen')
}
}
And this is what this function does.
My problem is with the onSubmit function which the code under the function is inmediately executing when the above function is called.
I hope you can help me! Thanks in advance.