Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React/GraphQL lifting a query up?

So there may be some obvious answer I’m unaware of, I’m not overly experienced with GraphQL so apologies in advance if it’s a stupid question.

Basically, I had a component, within which I grabbed some data from GraphQL, then passed that data to a function that filters the array, then passed the filtered results onto a child component, approximately like this

ChildComponent.tsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const { loading, error, data } = useQuery(SOME_RANDOM_QUERY, {variables: { id: Id, number: Value1 }})

const filteredItems: Item[] = data && getFilteredItems(data.items.nodes)
.
.
.
<SomeComponent itemsArray={filteredItems} />

And this worked. However, then it turned out I need the GraphQL data in another, sibling component, so I have to lift up this query. And I did:

ParentComponent.tsx

const queryResults = useQuery(SOME_RANDOM_QUERY, {variables: { id: Id, number: Value1 }})
.
.
.
<ChildComponent itemsList={queryResults?.data?.items?.nodes} />

ChildComponent.tsx

const ChildComponent: React.FC<{
  itemsList: Item[]
}> = ({ itemsList }) => {

const filteredItems: Item[] = itemsList && getFilteredItems(itemsList)
    .
    .
    .
    <SomeComponent itemsArray={filteredItems} />

And now this doesn’t work, it’s throwing an error, saying it "Cannot read properties of undefined" within the SomeComponent. Which makes me think the code runs before the query results are back somehow.

Any idea what’s causing this, and why it worked when the query was in the same file, but now when it’s passed through props, it suddenly doesn’t work?

>Solution :

Since graphql is basically an async api call (component get rendered whether or not the api call had ended), the child component get rendered even while the data is not received, meaning undefined gets passed until data is retrieved

you can add a loading component in the meantime

if(loading){
  return <loadingComponent/>
}

return <SomeComponent itemsArray={filteredItems}/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading