Home > Enterprise >  Cannot reach datas details with map function
Cannot reach datas details with map function

Time:11-13

function Clothes() {
  const { loading, error, data } = useQuery(GET_CLOTHES);
  const [products,setProducts] = useState([]);
  const [index,setIndex] = useState(0)

  useEffect(() => {
    if (data) {
      setProducts(data.AllItem);
      console.log(data.AllItem)
    }
      },[data,products]);

 
/*
  useEffect(() => {
    if(!loading && data){
        setProducts(data);
    }
  }, [loading, data])
*/
if (loading) return 'Loading...'               
if (error) return `Error! ${error.message}`


  return (
   <section className='section'>
     <div className='title'>
       <h2>
       </h2>
       {
         products?.map((product,index) => {
           //const {gallery} = product;
           return <img src = {product.gallery} />
         })
       }
     
     </div>
   </section>
  )
}

export default Clothes;

graphql schema

Hello everyone I have a issues with map function. I am getting data from my graphql but when I was trying to fetch them in my console.log I can see just undefined. Thank you in advance

CodePudding user response:

Try settings the data directly to the products state (remove the array) like ths:

const [products,setProducts] = useState(data);

CodePudding user response:

few pointer the may help

 transform the reponse and filter the items as needed

  const { loading, error, data = [] } = useQuery(GET_CLOTHES);
  const [products,setProducts] = useState(data);
  const [index,setIndex] = useState(0)

  const transformedResponse = useMemo(() => {
    try {
    // put checks and use try catch to handle errors
    const productsList = [];

    // check for null data
    const items = data ?? []

    for (const category of items) {
      const products = category?.products ?? [];
      productsList.push(...products)
    }

    return productsList
   } catch(error) {
      // log error 
      return []
   }
  }, [data)]

  return (
     ...
     {
       transformedResponse.map(prod => {

          return (<Prod key={prod.id} {...prod} />)
       }
     }
  )

Docs on working with arrays

Hope it helps

  • Related