Home > Software design >  Nested Query fetch Data
Nested Query fetch Data

Time:11-14

console.log

Hello everyone, I am trying to fetch my datas from graphlq however I can fetch to first data from array but when I try reach one of the nested array I got undefined. How I can solve this issue.

CodePudding user response:

  1. You don't need to keep data as a state variable
  2. data will be undefined until loading is false. The first pass through your console.log it will be undefined.

A typical pattern might be:

function Clothes() {
  const { loading, error, data } = useQuery(GET_CLOTHES);
  if (data) {
    … render the data
  } else if (error) {
    …handle the error
    return <Error /> // return an error component
  } else return <Loading /> // return a spinner or other progress indicator
}

Note that your function must return a jsx component - it cannot return a string.

CodePudding user response:

Ok. First of all, categories is an array, so products isn't defined as a property in the array. Its items do have the products property.

Second of all, products is a derived state. You do not need make a separate it as its own useState

import {useState, useEffect,useMemo} from 'react';
import { gql, useQuery } from '@apollo/client';
import {GET_CLOTHES} from "./GetClothes.js"
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';


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

  if (loading) return 'Loading...'               
  if (error) return `Error! ${error.message}`

  return <div>
    {
      data.categories.flatMap(x => x.products).map(product => {
        if (product.name === 'clothes') { //filter 
          // Iterate through products.products to obtain the product data.
          const {name,brand,description,gallery,category} = product;
          return <p>{name}</p>
        } else {
          return null;
        }
      })
    } 
  </div>
}

export default Clothes;
  • Related