Search code examples
javascriptreactjsnext.jsstrapi

Fetching data from strapi to next.js but response defer from the API URL


I'm fetching data from a Strapi app to my Next.js app. I'm filtering and populate the data to get it by Brand and to populate the image data.

Here is my function getStrapiData():

async function getStrapiData(path: string): Promise<StrapiData> {
  const baseUrl = "http://127.0.0.1:1337"
  const productQuery = qs.stringify({
    populate: {
      images: {
        fields: ["url", "alternativeText"],
      },
    },
    product_tags: {
      fields: ["name"],
    },
    filters: {
      brand: {
        name: "bonux",
      },
    },
  })

  const url = new URL(path, baseUrl)
  url.search = productQuery

  console.log(url.href)
  try {
    const response = await fetch(url.href)
    const data = (await response.json()) as StrapiData
    console.log(data)
    return data
  } catch (error) {
    console.error(error)

    throw error
  }
}

export default async function Web() {
  const strapiData = await getStrapiData("/api/products")

I have two console.log :

  1. console.log(url.href) return the URL to the API where I can see the products fetched
  2. console.log(data) returning the data response

What I don't understand is that the data between the two are not similar. In the number 2 I still have the previous data and in number 1 the new data after modification.

I don't know how to explain it better because I really don't understand and how to debug it.

What I see in the link with console.log 1:

{
  "data": [
    {
      "id": 40,
      "attributes": {
        "name": "L’original",
        "hook": "L’iconique lessive en poudre Bonux revient, accompagné aujourd’hui de ses versions concentrées et en capsules",
        "precautions": "",
        "description": "",
        "createdAt": "2024-04-22T09:41:45.248Z",
        "updatedAt": "2024-04-22T16:17:10.701Z",
        "publishedAt": "2024-04-22T09:44:29.748Z",
        "strapiName": "L’original",
        "code_ean": null,
        "info": "",
        "images": {
          "data": [
            {
              "id": 625,
              "attributes": {
                "url": "/uploads/Type_Group_423_67d79b78eb.png",
                "alternativeText": "image product"
              }
            }
          ]
        }
      }
    }
  ],
  "meta": {
    "pagination": {
      "page": 1,
      "pageSize": 25,
      "pageCount": 1,
      "total": 1
    }
  }
}

What I see in the console.log 2 (I only put the short version) :

    {
      data: [
        [
  {
    id: 8,
    attributes: {
      name: "Bonux Lessive concentrée L'Original (1,9L)",
      hook: 'Une valeur sûre pour la propreté de votre linge.',
      precautions: `<p><span style="font-size:12px;"><strong>MODE D'EMPLOI :</strong> 1 bouchon = 50 mL. À la main : doser 20 mL pour 5L d’eau, laver le linge et bien le rincer. Machine de 6-8Kg : Ajouter 25 à 30 mL au dosage prévu dans le tableau ci-contre.&nbsp;</span><br><br><img class="image_resized" style="width:66.74%;" src="/uploads/TABLEAU_DOSAGE_BONUX_3978673e18.png" alt="TABLEAU DOSAGE BONUX.png" srcset="/uploads/thumbnail_TABLEAU_DOSAGE_BONUX_3978673e18.png 245w, /uploads/small_TABLEAU_DOSAGE_BONUX_3978673e18.png 500w" sizes="100vw" width="500"><br><br><span style="font-size:12px;"><strong>PRÉCAUTIONS D’EMPLOI </strong>: Provoque une sévère irritation des yeux. Tenir hors de portée des enfants. Se laver soigneusement les mains après manipulation. Porter un équipement de protection des yeux. EN CAS DE CONTACT AVEC LES YEUX : Rincer avec précaution à l’eau pendant plusieurs minutes. Enlever les lentilles de contact si la victime en porte et si elles peuvent être facilement enlevées. Continuer à rincer. Si l’irritation oculaire persiste : consulter un médecin. EN CAS D'INGESTION : rincer la bouche. NE PAS faire vomir. Appeler immédiatement un CENTRE ANTIPOISON ou un médecin. En cas de consultation d’un médecin, garder à disposition le récipient ou l’étiquette. UFI : AX9N-FPD7-031Q-VKXD</span></p>`,
      description: `<p>Bonux revient en force avec sa lessive liquide L'Original fabriquée en France. Idéale pour le linge de toute la famille, elle offre une action nettoyante ultra- efficace, adaptée aux peaux les plus sensibles. Parfum longue durée aux notes subtilement fraîches !&nbsp;</p><p>Surprise ! Votre cadeau au dos de la bouteille !<br><br>&nbsp;</p><p><img class="image_resized" style="width:35.75%;" src="/uploads/VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png" alt="VISUEL AIRLABEL SCORE A+ (pour facing et dos de pack).png" srcset="/uploads/thumbnail_VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png 245w, /uploads/small_VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png 500w, /uploads/medium_VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png 750w, /uploads/large_VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png 1000w" sizes="100vw" width="1000"> &nbsp;<img class="image_resized" style="width:42.77%;" src="/uploads/ac_label_complet_horizontal_2_etoiles_db8bea14a5.png" alt="ac-label-complet horizontal 2 étoiles.png" srcset="/uploads/thumbnail_ac_label_complet_horizontal_2_etoiles_db8bea14a5.png 245w, /uploads/small_ac_label_complet_horizontal_2_etoiles_db8bea14a5.png 500w, /uploads/medium_ac_label_complet_horizontal_2_etoiles_db8bea14a5.png 750w, /uploads/large_ac_label_complet_horizontal_2_etoiles_db8bea14a5.png 1000w" sizes="100vw" width="1000"></p><p><br><span style="font-size:12px;"><span style="mso-ansi-language:FR;mso-bidi-language:AR-SA;mso-fareast-font-family:Calibri;mso-fareast-language:EN-US;mso-fareast-theme-font:minor-latin;">Dangereux - Respecter les précautions d’emploi.</span></span></p><p>&nbsp;</p>`,
      createdAt: '2023-02-22T04:52:22.660Z',
      updatedAt: '2023-12-01T09:35:54.214Z',
      publishedAt: '2023-02-22T04:52:57.554Z',
      strapiName: "Bonux - Bonux L'Original liquide",
      code_ean: '3760360760392',
      info: `<p><strong><u>Qualités et caractéristiques environnementales de l'emballage :</u></strong></p><figure class="table" style="width:994pt;"><table class="ck-table-resized" style="border-collapse:collapse;" border="0" cellpadding="0" cellspacing="0" width="1320"><colgroup><col style="width:11.11%;"><col style="width:11.11%;"><col style="width:11.11%;"><col style="width:11.11%;"><col style="width:11.11%;"><col style="width:11.11%;"><col style="width:11.11%;"><col style="width:11.11%;"><col style="width:11.12%;"></colgroup><thead><tr style="height:29.0pt;" height="39"><th class="xl73" style="height:29.0pt;width:124pt;" height="39" width="165">Possibilité de réemploi</th><th class="xl73" style="border-left-style:none;width:121pt;" width="161">Rechargeabilité</th><th class="xl73" style="border-left-style:none;width:132pt;" width="175">Possibilité de compostage</th><th class="xl74" style="border-left-style:none;width:105pt;" width="139">Taux de recyclabilité</th><th class="xl77" style="width:101pt;" width="134">Mention recyclabilité</th><th class="xl76" style="border-left-style:none;width:103pt;" width="137">% de matières recyclées<span style="mso-spacerun:yes;">&nbsp;</span></th><th class="xl75" style="width:115pt;" width="153">% de Substances dangereuses<span style="mso-spacerun:yes;">&nbsp;</span></th><th class="xl73" style="border-left-style:none;width:101pt;" width="134">% de Perturbateurs endocriniens</th><th class="xl73" style="border-left-style:none;width:92pt;" width="122">Primes et pénalités</th></tr></thead><tbody><tr style="height:43.5pt;" height="58"><td class="xl78" style="border-top-style:none;height:43.5pt;width:124pt;" height="58" width="165">Emballage non réemployable</td><td class="xl78" style="border-left-style:none;border-top-style:none;width:121pt;" width="161">Emballage non rechargeable</td><td class="xl78" style="border-left-style:none;border-top-style:none;width:132pt;" width="175">Emballage non compostable</td><td class="xl79" style="border-left-style:none;border-top-style:none;width:105pt;" width="139">98,60%</td><td class="xl80" style="border-left-style:none;border-top-style:none;width:101pt;" width="134">Emballage entièrement recyclable</td><td class="xl78" style="border-left-style:none;border-top-style:none;width:103pt;" width="137">0</td><td class="xl78" style="border-left-style:none;border-top-style:none;width:115pt;" width="153">0</td><td class="xl78" style="border-left-style:none;border-top-style:none;width:101pt;" width="134">0</td><td class="xl78" style="border-left-style:none;border-top-style:none;width:92pt;" width="122">&nbsp;</td></tr></tbody></table></figure><p><strong><u>Qualités et caractéristiques environnementales du produit :</u></strong></p><figure class="table" style="width:468pt;"><table class="ck-table-resized" style="border-collapse:collapse;" border="0" cellpadding="0" cellspacing="0" width="623"><colgroup><col style="width:50%;"><col style="width:50%;"></colgroup><thead><tr style="height:29.0pt;" height="39"><th class="xl73" style="height:29.0pt;width:162pt;" height="39" width="215">% de Substances dangereuses<span style="mso-spacerun:yes;">&nbsp;</span></th><th class="xl74" style="border-left-style:none;width:306pt;" width="408">% de Perturbateurs endocriniens</th></tr></thead><tbody><tr style="height:43.5pt;" height="58"><td class="xl75" style="border-top-style:none;height:43.5pt;width:162pt;" height="58" width="215">0</td><td class="xl76" style="border-left-style:none;border-top-style:none;width:306pt;" width="408">Ne contient pas de substances PBT/vPvB ≥ 0,1 % évaluées conformément à l'annexe XIII du règlement REACH<span style="mso-spacerun:yes;">&nbsp;</span></td></tr></tbody></table></figure>`,
      images: {
        data: [
          {
            id: 615,
            attributes: {
              url: '/uploads/BONUX_LIQUIDE_L_ORIGINAL_3760360760392_49e4f45232.png',
              alternativeText: null
            }
          }
        ]
      }
    }
  },
  {
    id: 9,
    attributes: {
      name: "Bonux L'Original ",
      hook: "Le retour de l'iconique poudre Bonux.",
      precautions: "Mode d'emploi : \n" +
        "Verser la quantité (indiquée sur l'emballage du produit) dans le compartiment lessive de votre machine à laver (indiqué par le chiffre II).\n" +
        "Machine de 6-8kg : rajouter 30g au dosage prévu (se référer aux indications données sur l'emballage du produit).\n" +
        'Pour doser, utiliser une cuillère à soupe dédiée ou un gobelet gradué. \n' +
        "A la main : 2 cuillères à soupe = 30g + 5L d'eau tiède. \n" +
        "Recommandations d'usage : Ne pas utiliser sur la laine, le cachemire et la soie. Bien respecter les consignes de lavage des articles. Ne pas surdoser la machine. A utiliser à partir de 30°C.\n" +
        '\n' +
        '\n' +
        'Contient : Disilicate de sodium, Acide benzènesulfonique, dérivés alkyles en C10-13, sels de sodium ; Alcools C12-15 ramifiés et linéaires, éthoxylés.\n' +
        '\n' +
        "Précautions d'emploi : Provoque des graves lésions des yeux. Provoque une irritation cutanée. Tenir hors de portée des enfants. Se laver soigneusement les mains après manipulation. Porter un équipement de protection des yeux/du visage. Porter des gants de protection. EN CAS DE CONTACT AVEC LES YEUX : Rincer avec précaution à l'eau pendant plusieurs minutes. Enlever les lentilles de contact si la victime en porte et si elles peuvent être facilement enlevées. Continuer à rincer. Si l'irritation oculaire persiste, consulter un médecin. EN CAS D'INGESTION : rincer la bouche. NE PAS faire vomir. Appeler immédiatement un CENTRE ANTI-POISON ou un médecin. En cas de consultation d'un médecin, garder à disposition le récipient ou l'étiquette. Éliminer le récipient conformément à la réglementation locale.\n" +
        'UFI : 9DVE-N03H-R00M-VHEG',
      description: `<p>Bonux revient dans son format iconique : la lessive en poudre ! Bonux poudre L'Original est idéale pour un linge éclatant de blancheur. Son action détachante et sa formule active au bicarbonate vous garantit un lavage impeccable ! Sans conservateurs, elle est parfaitement adaptée aux peaux même les plus sensibles.<br>Surprise ! Votre cadeau dans la boîte !<br><br>&nbsp;</p><p><img class="image_resized" style="width:35.75%;" src="/uploads/VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png" alt="VISUEL AIRLABEL SCORE A+ (pour facing et dos de pack).png" srcset="/uploads/thumbnail_VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png 245w, /uploads/small_VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png 500w, /uploads/medium_VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png 750w, /uploads/large_VISUEL_AIRLABEL_SCORE_A_pour_facing_et_dos_de_pack_42c299dbc6.png 1000w" sizes="100vw" width="1000"> &nbsp;<img class="image_resized" style="width:42.77%;" src="/uploads/ac_label_complet_horizontal_2_etoiles_db8bea14a5.png" alt="ac-label-complet horizontal 2 étoiles.png" srcset="/uploads/thumbnail_ac_label_complet_horizontal_2_etoiles_db8bea14a5.png 245w, /uploads/small_ac_label_complet_horizontal_2_etoiles_db8bea14a5.png 500w, /uploads/medium_ac_label_complet_horizontal_2_etoiles_db8bea14a5.png 750w, /uploads/large_ac_label_complet_horizontal_2_etoiles_db8bea14a5.png 1000w" sizes="100vw" width="1000"></p><p><br><span style="font-size:12px;"><span style="mso-ansi-language:FR;mso-bidi-language:AR-SA;mso-fareast-font-family:Calibri;mso-fareast-language:EN-US;mso-fareast-theme-font:minor-latin;">Dangereux - Respecter les précautions d’emploi.</span></span></p><p>&nbsp;</p>`,
      createdAt: '2023-02-22T04:58:09.956Z',
      updatedAt: '2023-04-21T08:06:20.585Z',
      publishedAt: '2023-02-22T04:58:12.092Z',
      strapiName: "Bonux - Bonux L'Original poudre",
      code_ean: null,
      info: null,
      images: {
        data: [
          {
            id: 544,
            attributes: {
              url: '/uploads/BONUX_Lessive_Poudre_L_Original_2kg_409fa3101a.png',
              alternativeText: null
            }
          }
        ]
      }
    }
  },
...
      ],
      meta: { pagination: { page: 1, pageSize: 25, pageCount: 1, total: 4 } }
    }

Solution

  • By default, Next.js automatically caches the values returned by the fetch API. If you want your data is always up to date, you can disable caching by adding a no-cache option like this:

    fetch('https://...', { cache: 'no-store' })
    

    For more details, refer to the documentation.