I have JSON data stored in a file titled recipes.json (it's local) and I'm using state hooks and storing that data in a state variable titled "recipes". For reference,
here's local .json data structure:
[
{"id": "0001",
"title": "Chicken Pot Pie",
"url": "https://www.pillsbury.com/recipes/classic-chicken-pot-pie/1401d418-ac0b-4b50-ad09-c6f1243fb992",
"time": {
"prepTime": 25,
"cookTime": 40
},
"ingredients": [
"CHICKEN "
]
},
Here's the state variable declaration and assignment:
const [recipes, setRecipes] = useState([]);
useEffect(() => {
const fetchRecipes = async () => {
const response = await fetch('recipes.json');
const recipesData = await response.json();
setRecipes(recipesData);
};
fetchRecipes();
}, []);
I have an array that I know is containing a dynamic ingredient list and am printing it to the user at any given time to display what's contained within. It's a variable titled allIngredients.
I'm trying to run a for loop through the diffrent json objects by id, per id map() the ingedients into an array arrayToCheck, and then compare that finished-per-recipe arrayToCheck to the user-created allIngredients, but I'm getting an error in my function: "The parser expected to find a '}' to match the '{' token here." I know it's no where else in my code because I haven't altered anything else and it was functional before adding this block:
const useRecipes = () => {
let arrayToCheck = [];
for (recipes.id; recipes.length; recipes.id++) {
recipes.map((map.recipe) => {
arraytoCheck = arrayToCheck.push(recipe.ingredients.toUpperCase())
if (arrayToCheck.sort() === allIngredients.sort()) {
return recipe.title;
}
})
arrayToCheck = [];
}
}
I know this may seem complicated (I'm newer to Stack Overflow, so ask any clarifying questions. Thanks in advance for the assistance.
on the forth line inside useRecipes try changing
recipes.map((map.recipe) => {
to
recipes.map((recipe) => {
but since you are not returning from map, you can use a normal loop instead of map.
Update
Notes:
array.push(...) automatically adds the new element to the array so the is no need to replace the whole array.
arrayToCheck.push(recipe.ingredients.toUpperCase()); //this is enough no need for arrayToCheck =
it is not clear what are you trying to achieve when comparing two sorted arrays check array comparison here
what is the point from passing recipeTitle to the method when you are not using it inside the loop and how can you rely on its value when it is being replaced all the time and you will always end up getting the last value.
and it is not clear what is the purpose of the outer loop looping over the id of recipes !!
take some time to understand javascript and loops