0

i've problem, idk why but i can't use my json file for my website...

if i try call the json, it's good but i can't use information... if you have solution, tell me pls T-T

i've test all but nothing work...

entity = fetch("./entity/entity.json")
  .then(response =>{return response.json()})

console.log(entity) /*output: 
                    Promise {<pending>}
                    __proto__: Promise
                    [[PromiseState]]: "fulfilled"
                    [[PromiseResult]]: Array(3)
                        0: {id: "1", title: "inventory 1", description: "l'objet 1 de l'inventaire", price: 50, img: false}
                        1: {id: "2", title: "inventory 2", description: "l'objet 2 de l'inventaire", price: 25, img: false}
                        2: {id: "3", title: "inventory 3", description: "l'objet 3 de l'inventaire", price: 15, img: false}
length: 3
__proto__: Array(0)*/ 


console.log(entity[0]) //output : undefined

tks.

  • It should be `fetch("./entity/entity.json").then(response => response.json()).then(json => { console.log(json); })`. But if you want to use your `entity` variable, you must use [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). – kosmos Dec 31 '20 at 10:15
  • why don't you try requiring it – Abishek Kumar Dec 31 '20 at 10:16

1 Answers1

0

You have to either stay in the promise chain.

fetch("./entity/entity.json")
  .then(response => response.json())
  .then(entity => {
    console.log(entity);
    console.log(entity[0]);
  });

Or use the async / await syntax to store the result in a variable.

(async () => {
  const response = await fetch("./entity/entity.json");
  const entity = await response.json();
  console.log(entity);
  console.log(entity[0]);
})();

This is because of fetch returning a Promise. So when doing entity = fetch() you store that returned promise in the entity variable. One of the two methods above allow you to extract the values from that promise.

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32