Where To Make Apollo Queries In React

I’m trying to wrap my head around Apollo. I’ve read through the docs… it’s quite possible that my answer is there, but I’m too dumb to parse it out.

Say that we have vehicles in inventory. We want to display a vehicle list of those in inventory and their attributes. The UI looks like…

       <Image />
           <Year />
           <Make />
           <Model />

What components call for the data? For instance, <VehicleList> (or its container) could query all vehicles in its list, complete with images, year, makes, models, etc and pass those down as props.

Or<VehicleList> could query for a list of vehicles, pass that list as props, and then each Vehicle could query its own image, year, make, model, etc.

But it seems like the goal of GraphQL is colocating data and UI. So the Apollo/GraphQL way seems to be have each <Image> component query its own image. Is that the approach? VehicleList generates a list of vehicles, <Vehicle> passes its vehicle Id to its children. And the children that render data make the query?

In order to keep your components less coupled to GraphQL I personally think it’s a good idea to do fewer queries and pass the data down. That will make the data loading much clearer, and make your presentational components more reusable.

You can use fragments in cases where you feel yourself duplicating lots of fields in different queries, or in a case where a component is used in many places.

GraphQL has a lot of potential benefits, and colocating with UI components is one that I think should be used sparingly. Other main benefits are a really flexible API that lets you write the UI data needs without changing server endpiints, having great developer tools, and a strongly typed API.

1 Like

Thanks for the quick reply and working through my typos (I didn’t realize if tags aren’t inside of back tics, they don’t show. Sorry!).

I greatly appreciate your feedback. I’ve always passed the data down, but I listened to a JS Air episode where Kent Dodds loved colocating the graphql query with the component. I understand why this could be helpful for huge teams.

Thank you for the validation that I’m not doing it wrong. :slight_smile: I’m getting use to the Apollo / GraphQL pattern and am becoming a big fan. It’s great work!

1 Like