如何在反应中为 formData 创建 if else?
How can I create if else for formData in react?
如果用户不需要添加头像但仍然创建一个团队,我正在尝试实现,但我遇到的问题是如果用户不在表单中添加头像会导致错误 file: undefined
下面是我的 handleSubmit 代码:
const handleSubmit = async (event) => {
event.preventDefault();
// upload image to server
const formData = new FormData();
formData.append("file", imageSelected.raw);
const pictureUrl = await axios.post(
"/api/v1/teams/upload/image",
formData,
{
headers: { "Content-Type": "multipart/form-data" },
}
);
const teamAvatar = pictureUrl.data.data.imageUrl;
// after upload image to server get image data and send it to create team function
const payload = { title, mission, isSearchable, teamAvatar };
// Send post request for signup
const res = await axios.post("/api/v1/teams/team", payload);
// If no validation errors were found
if (res.data.validationErrors === undefined) {
// Clear any errors
setErrorsArr([]);
// Hide the errors component
setShowErrors(false);
// Toggle the modal
toggleModal();
// Go to team management page
NextRouter.push(`/team/${res.data}`);
// console.log("payload", payload);
} else {
// Set errors
setErrorsArr(res.data.validationErrors.errors);
// Show the errors component
setShowErrors(true);
}
};
我如何为 formData 创建 if else 语句来帮助用户不需要添加头像但仍然可以创建团队
使用
if(imageSelected){
formData.append("file", imageSelected.raw);
}
如果用户不需要添加头像但仍然创建一个团队,我正在尝试实现,但我遇到的问题是如果用户不在表单中添加头像会导致错误 file: undefined
下面是我的 handleSubmit 代码:
const handleSubmit = async (event) => {
event.preventDefault();
// upload image to server
const formData = new FormData();
formData.append("file", imageSelected.raw);
const pictureUrl = await axios.post(
"/api/v1/teams/upload/image",
formData,
{
headers: { "Content-Type": "multipart/form-data" },
}
);
const teamAvatar = pictureUrl.data.data.imageUrl;
// after upload image to server get image data and send it to create team function
const payload = { title, mission, isSearchable, teamAvatar };
// Send post request for signup
const res = await axios.post("/api/v1/teams/team", payload);
// If no validation errors were found
if (res.data.validationErrors === undefined) {
// Clear any errors
setErrorsArr([]);
// Hide the errors component
setShowErrors(false);
// Toggle the modal
toggleModal();
// Go to team management page
NextRouter.push(`/team/${res.data}`);
// console.log("payload", payload);
} else {
// Set errors
setErrorsArr(res.data.validationErrors.errors);
// Show the errors component
setShowErrors(true);
}
};
我如何为 formData 创建 if else 语句来帮助用户不需要添加头像但仍然可以创建团队
使用
if(imageSelected){
formData.append("file", imageSelected.raw);
}