Home > Software engineering >  Showing attributes of an object with Svelte and Strapi v4
Showing attributes of an object with Svelte and Strapi v4

Time:01-02

I am using Strapi v4 and Svelte for a project (I am also quite new at developping, sorry but my question may then be basic). I fetch my Strapi datas from my localhost and get them into the console log, no problem. With GraphQL, I get datas as follows, for example :

"produits": {
  "data": [
    {
      "id": "1",
      "attributes": {
        "reference": "MEV620001"
      }
    }

My problem is when rendering them with Svelte, I can only get the ID and don't know how to show the attributes of each product. With Strapi v3, I could, but I cannot now with the changes how the datas are displayed with Strapi v4. My code in Svelte is :

<script>
import { onMount } from "svelte";

let produits = []

onMount(async () => {
    const response  = await fetch('http://localhost:1337/api/produits')
    produits = await response.json()
    console.log(produits)
})

</script>

{#if produits.data}
{#each produits.data as produit}
<h3>{produit.id}{produit.reference}</h3>  ///how to enter into the attributes with Strapi v4 ?///
<hr />
{:else}
<p>Chargement...</p>
{/each}
{/if}

With the above code, I get the "reference" as undefined in the front end, this is because the "reference" is inside the attributes of this particular id, and I don't know how to get inside the attributes to render them. Thanks a lot in advance for your great help.

CodePudding user response:

you need to access attributes then reference this can be done in your code using produit.attributes.reference

<script>
  import { onMount } from "svelte";

  let produits = [];

  onMount(async () => {
    const response = await fetch("http://localhost:1337/api/produits");
    produits = await response.json();
    console.log(produits);
  });
</script>

{#if produits.data}
  {#each produits.data as produit}
    <h3>{produit.id}{produit.attributes.reference}</h3> <!-- modified this line -->
    ///how to enter into the attributes with Strapi v4 ?///
    <hr />
  {:else}
    <p>Chargement...</p>
  {/each}
{/if}

  • Related