Using Apollo Client 2.0 with Redux in Wix React Native Navigation
In previous versions of Apollo, a Redux store could be used as the caching layer for Apollo Client. However, this no longer works with Apollo Client 2.0 as Redux support was dropped as to remove the dependency for developers who didn’t want to have to use it. You can read more about that decision here.
To use Redux and Apollo Client 2.0 together, you simply have to wrap your Apollo Provider with a Redux Provider like this:
<Provider store={store}>
<ApolloProvider client={client}>
<YourComponent/>
</ApolloProvider>
</Provider>
Integrate both providers with Wix Navigation using Higher Order Components
You can use a Higher Order Component (HOC) to reuse the logic wrapping your component with both providers as demonstrated above. Here’s an example of a HOC that will wrap your component with both providers, taking your component, Redux store, and Apollo Client as arguments.
apolloAndReduxProviderHOC = (WrappedComponent, store, client) => { class Enhance extends React.Component {
render () {
return (
<Provider store={store}>
<ApolloProvider client={client}>
<WrappedComponent {...this.props} />
</ApolloProvider>
</Provider>
)
}
}
return Enhance}
Now you can wrap your components automatically when registering them with Wix Navigation:
Navigation.registerComponent(name, () => apolloAndReduxProviderHOC(component, store, client));
And that’s how it works! One caveat though: HOCs don’t transfer over static properties automatically, so if you use static navigator styles for Wix Navigation, you’ll need to have those copied over. We can use hoist-non-react-statics
to auto copy those in our HOC. You’ll need to install that library first:
npm install --save hoist-non-react-statics
Here’s the complete HOC example with copied statics:
Now all your registered screens can access the Redux and Apollo stores, while maintaining any static properties they may have defined!
Closing Words
As a developer, I’ve always relied on the kindness of the online community to publish examples and tutorials for others. This is my first time sharing back by publishing an example online. I really do hope this post has been useful for you.
Comment below if you have trouble getting this example to work and I’ll do my best to get back to you as quickly as possible!
If you want talk more, chat about React or great typefaces, hit me up on Twitter @lucasmcgartland.