The full extent of my code. I downsized it here Need guidance! Trying to learn about fetch() and Promises to try and be more concise with my question.
The code essentially works. It's just that I don't know why it doesn't like it when I add another fetch()
export const addPlace = (placeName, streetName, city, region, postCode, country, location, image, coverImage) => {
return dispatch => {
let authToken;
dispatch(uiStartLoading());
dispatch(authGetToken())
.catch(() => {
alert("No valid token found!");
})
.then(token => {
authToken = token;
return image = fetch("myappURL/storeImage",
{
method: "POST",
body: JSON.stringify({ image: image.base64 }),
headers: {
Authorization: "Bearer " + authToken,
}
}
);
})
.catch(err => {
console.log(err);
alert("Oops! Something went wrong, please try again1")
dispatch(uiStopLoading());
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw(new Error());
}
})
.then(parsedRes => {console.log(parsedRes);
const placeData = {
name: placeName,
fullAddress: [streetName, city, region, postCode, country],
shortAddress: [city, region],
location: location,
image: parsedRes.imageUrl,
imagePath: parsedRes.imagePath,
coverImage: parsedRes.coverImageUrl, // what I want to add
coverImagePath: parsedRes.coverImagePath // what I want to add
}; // this is the output
return fetch("myappURL/places.json?auth=" + authToken, {
method: "POST",
body: JSON.stringify(placeData)
});
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw(new Error());
}
})
.then(parsedRes => {
console.log(parsedRes);
dispatch(uiStopLoading());
dispatch(placeAdded());
})
.catch(err => {
console.log(err);
alert("Oops! Something went wrong, please try again2")
dispatch(uiStopLoading());
});
};
};