Ad
How Do I Map An Array From GraphQL To A ResourceList Element?
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:
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
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad