Ad

How Do I Map An Array From GraphQL To A ResourceList Element?

- 1 answer

I've made a GQL query in which I receive data on all of my products as objects within an array. Here is one of the objects: Product Objects as it appears within the array

With this data, I am trying to map each individual product to a <ResourceItem> element within a <ResourceList>. However I am struggling to get this loading in correctly - I get nothing back on screen or in my console when logging. Would anyone be able to give me a hand?

Here is my GQL query:

const GET_PRODUCTS = gql`
  query getProducts {
    products(first: 50) {
      edges {
        node {
          id
          title
          featuredImage {
            originalSrc
          }
          metafields(first: 5) {
            edges {
              node {
                id
                key
                value
              }
            }
          }
        }
      }
    }
  }
`

...and here is my function to execute this:

// Retrieve all products
const GetProductList = ({ onProductSelected }) => {
  // Execute GET_PRODUCTS GQL Query
  const { loading, error, data } = useQuery(GET_PRODUCTS);

  // Loading & error management
  if (loading) return 'Loading...'
  if (error) return `Error - ${error}`

  // Return dropdown menu of all products
  return (
    <div>
      <Card>
        <ResourceList
          resourceName={{singular: 'product', plural: 'products'}}
          items={() => data.products.edges.map((product) => [
            {
              id: product.node.id,
              title: product.node.title
            },
          ])}
          renderItem={(item) => {
            const { id, title } = item;

            return (
              <ResourceItem id={id} accessibilityLabel={`View details for ${title}`}>
                <h3><TextStyle variation="strong">{title}</TextStyle></h3>
              </ResourceItem>
            )

          }}
        >
        </ResourceList>
      </Card>
    </div>
  )
}

Thanks!

(PS if it helps, this is the example I am loosely following: Resource List Example

Ad

Answer

You don't need to map, ResourceList handles the mapping for you just pass in the data.products.edge you want to map.

It should look like this

<ResourceList
  resourceName={{singular: 'product', plural: 'products'}}
  items={data.products.edges}
  renderItem={(item) => {
    const { id, title } = item;

    return (
      <ResourceItem id={id} accessibilityLabel={`View details for ${title}`}>
        <h3><TextStyle variation="strong">{title}</TextStyle></h3>
      </ResourceItem>
    )
  }}
>
</ResourceList>
Ad
source: stackoverflow.com
Ad