Home > front end >  Can't use data fetched from graphql
Can't use data fetched from graphql

Time:01-27

const Products = async()=> {
    try {
      const result= await API.graphql(graphqlOperation(listProducts));
      const products = result.data.listProducts.items;
      console.log(products);
      let y = []
      if (products){
       for (let x in products){
       y.push(x.name);
       }
      }
      console.log(y);
  
     } catch (err) { 
      console.log('error fetching products');
      }
      } ;

I am able to view the result but why does it show an array full of undefined items. o/p for y :

[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

CodePudding user response:

Its a bad idea to use for...in for looping, you can map the values instead of using a for...in or just use regular loop.

if (products){
    products.map((x) => y.push(x.name));
}
  •  Tags:  
  • Related