r/graphql • u/praell • Aug 07 '19
Apollo Client now with React Hooks!
Apollo just released react-apollo 3.0.0 with support for doing queries, mutations, and subscriptions through the react hooks api.
https://blog.apollographql.com/apollo-client-now-with-react-hooks-676d116eeae2
7
4
u/danielrearden Aug 07 '19
So I poked around the types and put together a spreadsheet for the differences between the two APIs.
https://docs.google.com/spreadsheets/d/1SdRcDezwePhrcN9CJrY0W03b33CdpjTAiOIBo1eIioE
Some notable differences:
subscribeToMore added to useQuery
onComplete and onError added to useQuery and useMutation
updateQueries dropped in useMutation (you shouldn't be using it anyway!)
onSubscribe and onSubscriptionComplete added to useSubscription
I suspect most folks would be fine to do a drop-in replacement like u/StarshipTzadkiel did.
1
1
u/rms7 Aug 08 '19
updateQueries dropped in useMutation (you shouldn't be using it anyway!)
Can you explain why we should updateQUeries in useMutation?
1
u/danielrearden Aug 08 '19
I meant that you shouldn't be using
updateQueries, whether withuseMutationor theMutationcomponent or the HOC. There's been a note in the docs aboutupdateQueriesbeing deprecated since forever. You can useupdateto achieve the same functionality.1
u/thepointer Aug 08 '19
Does `subscribeToMore` automatically unsubscribe when the component unmounts?
2
u/danielrearden Aug 08 '19
I haven't tried it but any subscriptions associated with an ObservableQuery should be unsubscribed when the query itself is torn down (which is what happens on unmount).
3
u/mieradi Aug 07 '19
This is incredible. I wasn't using Apollo Client for local state management because of how messy it was, but NOW...Well you get it.
2
u/danielrearden Aug 07 '19
The API looks almost identical to `react-apollo-hooks`, which is awesome. Has anyone tried migrating from `react-apollo-hooks` to the official library? I'd be curious to know if there are any gotchas.
2
u/StarshipTzadkiel Aug 07 '19
I tried this yesterday by doing a find and replace 'react-apollo-hooks' for '@apollo/react-hooks' and it worked just fine! Granted it was a small project but as far as I can tell the api is indeed identical.
1
u/vampiire Aug 07 '19
Those look really clean. My only confusion is on the lazy query why is the element order reversed? Is that a technical reason related to hooks? Would have been nice to keep the same “signature” as the mutation with 0 being the executor and 1 being the data / loading / error state.
2
u/smeijer87 Aug 07 '19 edited Aug 07 '19
No, there is no technical reason to return the properties in that order. They can return whatever they want however they want.
But there is more in the naming that I don't understand.
For example, why does the
mutationhas a property namedloading? Wouldn'tsubmittingbe a better fit?But indeed, it doesn't look very uniform:
const [execute, { loading }] = useMutation(SAVE_MESSAGE); const { data, loading } = useQuery(GET_MESSAGE); const [{ data, loading }, execute] = useLazyQuery(GET_MESSAGE);Also, it would have been nice if
datacould have been simplified. It sucks to get the query response from it:const { data, loading } = useQuery(...); const rocket = data && data.getRocketInventory; return ( <div>{rocket && rocket.name}</div> );1
u/danielrearden Aug 07 '19
The
dataproperty has to work that for two reasons: One, data itself could be potentially null and we need to be able to distinguish between that scenario and when the field itself is null. Two, you can request more than one root field in a single document, i.e.query { getRocketInventory getFirecrackerInventory }1
u/smeijer87 Aug 07 '19
The "data being null" is something I don't understand. Why can't data default to an empty object? I need to check the named property any way, don't I?
If I query
rockets, and let's assume the server returns the rocket. Thendataisnullwhile loading istrue. And as soon asloadingisfalse, I have bothdataas well asdata.rocketpopulated. Correct?I do understand the named keys in
data, as we can indeed include multiple root queries in a single run. And even alias them.But still, most (of my) queries contain a single root query. A special property for those cases would already be very helpful.
1
u/danielrearden Aug 07 '19
Apollo actually used to default to an empty object for data until the result was returned -- I believe that's changed recently.
The tricky thing is that data can end up null because of the way GraphQL handles errors and non-null fields. An error can "bubble up" the AST until hits a nullable field -- if it doesn't, then the whole data object is null. This is notably different from either the field itself being null or data returning as an empty object (which could happen if you end up with an empty selection set, for example because of
@skip).I could see some benefit to a "path" or "flatten" parameter to help cut down on boilerplate. Of course, especially now with hooks, there's nothing stopping you from wrapping your hook with another hook that would encompass that sort of logic.
1
u/vampiire Aug 07 '19
I responded above but the graphql spec itself states that data must either be null (in which case errors will be defined) or an object with named entries for each requested operation that hold their result data.
1
u/vampiire Aug 07 '19
I looked into it and the blog was incorrect. The actual code has them in the executor, queryState order
The reason they use loading is likely to be backwards compatible with the previous Apollo client / react Apollo. It has always been data, loading, error for both queries and mutations.
The reason for the data digging has to do with the graphql spec itself. Every response has to include a data property that is either null or an object with properties for each root query / mutation name. You’ll have multiple name entries if you do batch requests.
One way to get around this is with a consistent alias. So when you write your queries / mutations just set an alias called “result” (or whatever you want) to the name. Then you can always access data.result manually or write a wrapper that extracts data.result and returns it.
Say you have queryName() { ...fields }
Now you write
result: queryName(){ ...fields }
To alias it
1
u/AiexReddit Aug 08 '19 edited Aug 08 '19
Has anyone got this working with graphql-codegen yet? Any suggestions?
When I tried it I wasn't able to get it to compile as codegen uses ReactApollo.QueryProps which appears to no longer exist in version 3.0.
I'm exited to migrate over to the built in API for hooks but I love codegen too much too switch over until I can find a way to get them to work in harmony.
Edit:
Disregard, looks like they released a new version of codegen at the same time. I'll leave this comment here to help anyone else who might come across it:
https://blog.logrocket.com/graphql-code-generator-1-5-is-out/
I was successfully able to get it all upgraded smoothly with no code/API change, all I did was run:
yarn upgrade react-apollo@^3.0 yarn upgrade @graphql-codegen/cli@^1.5
Then re-generate the codegen file, find and replace all instances of react-apollo-hooks with @apollo/react-hooks and everything works beautifully.
0
Aug 07 '19
[deleted]
1
u/praell Aug 07 '19
Yep. This is definitely the most clean way to do mutation and queries, and at the same time being more verbose than both HoC's and Render prop pattern.
10
u/equal_odds Aug 07 '19
PRAISE THE LORD