I'm trying to achieve if user dont need add avatar but still create a team but i am having problem that if user don't add avatar in form it will cause an error saying file: undefined
Here is my following code for 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);
}
};
How can I create if else statement for formData that help user don't need to add avatar but still can create a team
Use
if(imageSelected){
formData.append("file", imageSelected.raw);
}