我正在使用 React/Firebase 在 firebase 中存储一些数据和图像。但是当图像上传时,它不会立即设置下载 URL 状态。所以我的数据第一次没有 img 值。但如果我再次点击发送按钮,它就会使用 img URL。我想立即/第一次使用我的其他数据执行此操作。 我想这可以用异步等待来完成,但我想不出正确的方法,请帮助我。
const [mobileDetail, setMobileDetail] = useState({
brand: '',
model: '',
userange: '',
price: null,
ram: null,
rom: null,
frontCamera: null,
rearCamera: null,
condition: '',
fingerprint: '',
status: '',
img: '', // this img value not sending first time
description: '',
});
const sendDataToDB = async () => {
try {
const docRef = await addDoc(collection(db, "mobiles"), {
mobileDetail
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
}
const Submitclicked = async (e) => {
e.preventDefault();
console.log(images);
if (images === null || images === undefined) {
console.log('not selected');
}
const storageRef = ref(storage, `images/${images.name}${v4()}`);
const uploadTask = uploadBytesResumable(storageRef, images);
uploadTask.on('state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
},
(error) => {
console.log('there is an error');
},
() => {
getDownloadURL(uploadTask.snapshot.ref)
.then(async (downloadURL) => {
if (downloadURL) {
setMobileDetail({ ...mobileDetail, img: downloadURL });
await sendDataToDB();
console.log(mobileDetail);
}
})
}
);
}