1

I am trying to fetch data from a (local) JSON file. I have no trouble accessing the first level of data within the JSON file (e.g. id, title, ingredients as a whole). However, the issue arises when I try to access/read/fetch the single ingredients.

By my understanding, x-for="ingredient in data.recipies.ingredients" should give me one instance of <p>TEST</p> for each ingredient per recipe. However, the output is empty. I am getting no console errors.

HTML/Alpine Markup:

<div x-data="data()">
  <template x-for="recipe in data.recipies">
    <div>
      <h3 x-text="recipe.title"></h3>
      <template x-for="ingredient in data.recipes.ingredients">
        <p>TEST</p>
      </template>
    </div>
  </template>
</div>

The JS file:

const data = () => {
    return {
        data: {
            recipies: [],
        },
        init() {
            fetch('src/recipies.json')
                .then((res) => {
                    return res.json();
                })
                .then((data) => {
                    this.data.recipies = Object.values(data)
                });
        },
    };
};

The JSON file:

{
    "aglioolio": {
        "id": 1,
        "title": "Aglio Olio + Chili",
        "ingredients": ["Spaghetti", "Olive oil", "Garlic", "Chili"]
    },
    "tortellinisoup": {
        "id": 2,
        "title": "Tortellini Soup",
        "ingredients": ["Tortellini", "Veggie Broth", "Chieves"]
    }
}
3
  • What happens if you replace your <template> tag with another tag? What's your reasoning for using it? It's not rendered, but meant to hold markup that may be used elsewhere. But you're not showing that here. dev.to/arafat4693/html-template-tag-explained-3859 Commented Apr 25 at 15:30
  • Shouldn't it be: x-for="ingredient in recipe.ingredients" ? Commented Apr 25 at 16:37
  • @TUPKAP Thank you very much, that was the mistake. I'm still learning. Commented Apr 25 at 17:49

1 Answer 1

0
<div x-data="data()" x-init="init()">
  <template x-for="recipe in data.recipies" :key="recipe.id">
    <div>
      <h3 x-text="recipe.title"></h3>
      <template x-for="ingredient in recipe.ingredients" :key="ingredient">
        <p x-text="ingredient"></p>
      </template>
    </div>
  </template>
</div>

    const data = () => {
    return {
        data: {
            recipies: [],
        },
        init() {
            fetch('src/recipies.json')
                .then((res) => res.json())
                .then((data) => {
                    this.data.recipies = Object.values(data);
                });
        },
    };
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.