pe73r / posterama

0 stars 0 forks source link

[example] Utiliser graphql plutot que le client shopify pour fetcher les données #1

Open beynar opened 3 years ago

beynar commented 3 years ago

npm i graphql urql

avec ca tu peux fetcher précisemment ce que tu veux, et par example les 250 premiers produits

import { createClient, Provider } from 'urql'

const client = createClient({
  url: `https://${STORE_DOMAIN}/api/2021-01/graphql.json`,
  fetchOptions: () => ({
    headers: {
      'X-Shopify-Storefront-Access-Token': API_TOKEN,
    },
  }),
})

import { useQuery } from 'urql'

const Test = ({}) => {
  return (
    <Provider value={client}>
      {typeof window !== 'undefined' && <Products />}
    </Provider>
  )
}

const productsQuery = /* GraphQL */ `
  query getAllProducts(
    $first: Int = 250
    $query: String = ""
    $sortKey: ProductSortKeys = RELEVANCE
    $reverse: Boolean = false
  ) {
    products(
      first: $first
      sortKey: $sortKey
      reverse: $reverse
      query: $query
    ) {
      pageInfo {
        hasNextPage
        hasPreviousPage
      }
      edges {
        node {
          id
          title
          vendor
          handle
          priceRange {
            minVariantPrice {
              amount
              currencyCode
            }
          }
          images(first: 1) {
            pageInfo {
              hasNextPage
              hasPreviousPage
            }
            edges {
              node {
                originalSrc
                altText
                width
                height
              }
            }
          }
        }
      }
    }
  }
`
const Products = () => {
  const [result, reexecuteQuery] = useQuery({
    query: productsQuery,
  })

  if (result.error) return <div>error</div>
  return (
    <div>
      {result.data.products.edges.map(({ node: product }) => {
        const { id, title } = product
        return <div key={id}>{title}</div>
      })}
    </div>
  )
}

export default Test
beynar commented 3 years ago

Pour tester des requêtes graphql je te conseille d'installer un client tel que altair graphql