For me , it was one of the most time consuming task as a beginner. There was no proper article related to integrating react-native, react-navigation and Apollo Client.
Installing the packages:
Create a react-native project .
react-native init ProjectName
Install Package react-navigation and apollo-client
Don't use apollo-boost package , it will give error.
npm i -S react-navigation apollo-client apollo-cache-inmemory apollo-link-http graphql graphql-tag react-apollo
Configuring
- React-navigation
import { createStackNavigator, createDrawerNavigator, createAppContainer } from ‘react-navigation’;
import HomeScreen from ‘./screens/HomeScreen’
import GoalScreen from ‘./screens/Goals/Goals’;
const MainNavigator = createDrawerNavigator({
Home: {
screen: HomeScreen ,// HomeScreen Component
path: 'auth/:token'
},
Goals: {
screen: GoalScreen,// GoalScreen Component
path: 'goals/:id'
}
}, {
initialRouteName: “Goals”,
})
const App = createAppContainer(MainNavigator)
- Apollo-client
HomeScreen.js
import { ApolloProvider } from 'react-apollo'
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import MainNavigator from './MainNavigator'
const withProvider = (Component,navigationOptions)=>{
const cache = new InMemoryCache();
const link = new HttpLink({
uri: 'http://myurl.com',
})
const client = new ApolloClient({
link,
cache,
defaultOptions
});
return class extends React.Component {
static navigationOptions = navigationOptions;
render(){
return(
<ApolloProvider client={client}>
<Component props={this.props} client={client}/>
</ApolloProvider>
)
}
}
}
const GoalScreen = createStackNavigator({
Goals: {
screen: MainNavigator,// Component nested inside Goals
}
})
export default Goals = withProvider(createAppContainer((GoalScreen)),
{
header:"Goals"
}
);
I have passed client to the component. Now we can use this client props to fire query and mutations. For eg:
this.props.client.query({
query:MY_QUERY,
variables:{name:value}
})
this.props.client.mutate({
mutation:MY_MUTATION,
variables:{name:value}
})
This made my day. Using <Query/> for running graphQL queries was cumbersome.
My example react native app: PHGoals - Apps on Google Play I have made this app during maker festival 2.0. Do upvote on product hunt.