0

If I have a simple UI component that displays some some product info. And it contains it's own fragment like so:

const Product = ({detail}) => {

  const data = useFragment(
    graphql`
        fragment Product_detail on Product {
            title
            detail
        }
    `,
    detail
  )

  return (
     <div>
       <h1>{data.title}</h1>
       <p>{data.detail}</p>
     </div>
}

And it is use it inside a parent component that looks like this:

const Page1 = ({content}) => {

  const data = useFragment(
    graphql`
        fragment Page1_content on Page1Info {
            oneProduct {
              ...Product_detail
            }
        }
    `,
    detail
  )

  return <Product detail={data.oneProduct}/>
}

How could I reuse the Product component on a different page, where the parent's graphql fragment returns an array of Products, instead of just one product?

const Page2 = ({content}) => {

  const data = useFragment(
    graphql`
        fragment Page2_content on Page2Info {
            allProducts { //returns an array of products
              title
              ...Product_detail
            }
        }
    `,
    detail
  )

  return (
    <div>
       {data.allProducts.map(product => <button>{product.name}</button>)}

       {*/Display the product detail of the product who's button is clicked*/}
       <Product detail={data.allProducts}/>
    </div>
}

I am using Relay as my graphql client. But I'm assuming the principal are the same across all clients?

davidx1
  • 3,525
  • 9
  • 38
  • 65
  • 1
    just use `useState` to save choosen index, pass only one 'record' ? – xadm May 26 '20 at 00:01
  • @xadm You mean just `` for example? Oh man, I didn't realize you could do that. I thought you had to do something fancy with the graphql query itself... – davidx1 May 26 '20 at 00:21
  • IMHO you don't even need a `useFragment` inside ``, you can just pass data as props – xadm May 26 '20 at 00:27
  • @xadm No, not in this example. This is just a dummed down thing to illustrate my problem. The actual code has a much more complex fragment inside Product, and the component will be reused in a few different places. So I think it's best to keep the fragment colocated with the display code. – davidx1 May 26 '20 at 00:31
  • 1
    sure, "it depends" (refetching/completness etc.) – xadm May 26 '20 at 00:36

0 Answers0