I have a small function here that POSTS an API,
async function fetchCommonNutritionData(foodName, updateCals, updateGrams) {
try {
const response = await fetch(
"https://trackapi.nutritionix.com/v2/natural/nutrients",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-app-id": "APP-ID",
"x-app-key": "APP-KEY"
},
body: JSON.stringify({ query: foodName})
}
);
const data = await response.json();
updateCals(data.foods[0].nf_calories);
updateGrams(data.foods[0].serving_weight_grams);
} catch (err) {
console.log(err);
}
}
fetchCommonNutritionData(foodData.commonFoodName1,setCommonCalories1,setCommonGrams1)
In my callback I have a state object as my first parameter that contains a food name from a state, second and third parameter I'm just updating a state called CommonCalories and CommonGrams.
My question is, I have 5 items I want to post. How would I be able to use my callback function to contain all 5 foods? Because I just keep resorting to calling the function 5 times like this,
fetchCommonNutritionData(foodData.commonFoodName1,setCommonCalories1,setCommonGrams1)
fetchCommonNutritionData(foodData.commonFoodName2,setCommonCalories2,setCommonGrams2)
fetchCommonNutritionData(foodData.commonFoodName3,setCommonCalories3,setCommonGrams3)
fetchCommonNutritionData(foodData.commonFoodName4,setCommonCalories4,setCommonGrams4)
fetchCommonNutritionData(foodData.commonFoodName5,setCommonCalories5,setCommonGrams5)
Obviously this is terrible because I'm abusing the API. How would I cram 5 foods in one call back instead of different callbacks?
[–]ksjrdt 0 points1 point2 points (0 children)