Query data with GraphQL in React with data from a previous query

454 Views Asked by At

So generally I have no problem with querying or mutating data with apollo react and GraphQL. But there is one thing I just don't get: Assuming I have a query that gets an Id of an arbitrary entity like so:

const Query = graphql(
  baseNodeQuery([
    'entityId',
    'entityLabel'
  ], 'employment_reference_preset'), {
    options: {
      variables: {
        filter: {
          type: "employment_reference_preset"
        },
        limit: 1000,
        offset: 0
      }
    }
  })
(ExampleComponent);

baseNodeQuery is a custom function which takes some parameters to prepare a query with gql(). But anyway, in my ExampleComponent I can use the data like this:

const EmploymentReferencePresetEntity = ({data: {loading, error, nodeQuery}}) => {
  if (loading) {
    return <p>Loading...</p>;
  }
  if (error) {
    return <p>{error.message}</p>;
  }

  return (
    <div>
      //do something with the data form nodeQuery
    </div>
  )
};

But what about when I want to use the Id I got from my previous query to make a second query and use that Id as filter? When I'm returning another graphql query in my ExampleComponent like before, I'm getting an error that I'm not returning a valid react component. So how am I supposed to do this?

Thanks in advance!

2

There are 2 best solutions below

0
On

The way that I've been able to do this in the past was by separating the "child" query into its own component.

Let's say you have a Solar System component that shows you all the planets. So you have a query to return planets without details, and another query called planetDetails or something. You create your SolarSystem component and wrap that with your parent query, then each planet in that will load another component and pass the planetID as a prop to it. On that component, you wrap the planetDetails query and take the prop "planetID" for your query.

I know it's not the best example, hope it helps.

0
On

It might serve your purpose to make and resolve the second call in your EmploymentReferencePresetEntity before you return the JSX. Like this:

const EmploymentReferencePresetEntity = ({data: {loading, error, nodeQuery}}) => {
  if (loading) {
    return <p>Loading...</p>;
  }
  if (error) {
    return <p>{error.message}</p>;
  }

  ... make and resolve your second query here like...
  const secondQueryResult = await secondQuery(nodeQuery)

  return (
    <div>
      //do something with secondQueryResult
    </div>
  )
};