React - using Offix Hooks
ApolloOfflineClient
is compatible with all of the official Apollo React Hooks such as useQuery
, useMutation
and useSubscription
.
For a quickstart, a simple React todo app can be found in the example folder.
The react-offix-hooks
library provides an additional useOfflineMutation
React hook for performing offline mutations.
Note: react-offix-hooks
is experimental. Please try it and log any issues to help us improve it.
#
App InitializationIn a normal React application that uses Apollo Client, the client is created at startup and the root component is wrapped with ApolloProvider
.
Because client.init()
needs to be called and this is an asynchronous function call, an extra step is needed. The root ApolloProvider
also needs to be wrapped with ApolloOfflineProvider
for the useOfflineMutation
hook to work.
Below is a boilerplate example that can be used.
In the example above, the following happens.
- An
ApolloOfflineClient
is created. useState()
is used to set a boolean that will betrue
once the client is initialized.client.init()
is called inside auseEffect
call making sure the initialization happens only once.- If
initialized
is true, then the application is rendered including theApolloOfflineProvider
and theApolloProvider
. Otherwise a loading screen is shown.
#
useOfflineMutationuseOfflineMutation
is similar to useMutation
but it internally calls client.offlineMutate
. useOfflineMutation
will throw an offline error if the mutation was made while offline which needs to be handled in the client.
#
State PropertiesuseOfflineMutation
provides additional state that can be used to build UIs.
The following properties are available on the state
returned from useOfflineMutation
called
- true when the mutation was called.data
- the result of the mutation.error
- error returned from the mutation (not including offline errors).hasError
- true when an error occurred.loading
- true when a mutation is in flight or when an offline mutation hasn't been fulfilled yet.calledWhileOffline
- true when mutation was called while offline.
Example:
Before the mutation is called:
After the mutation is called while online:
#
useNetworkStatusThe useNetworkStatus
hook can be used to build components that render differently depending on the network state. The hook returns true
when the network is online and false
when the network is offline. The hook uses a listener to return a new value when the network status changes.
Example: