Connecting app with GraphQL server - ScalaConsultants/react-example-app GitHub Wiki
This project is using GraphQL client Apollo to fetch data from server (simple database on graph.cool).
npm install react-apollo --save
import { ApolloClient, createNetworkInterface , ApolloProvider} from 'react-apollo'
const networkInterface = createNetworkInterface({
uri: 'https://api.graph.cool/simple/v1/cj3mzkoyv3b3e0189nnt1gh3v' // link to server
})
const client = new ApolloClient({
networkInterface: networkInterface
})
We need to add Apollo provider on elements which will have access to GraphQL data. If we want add this for whole app we can wrap React Router provider as in this example:
<ApolloProvider client={client}>
<Provider store={store}>
[...]
</Provider>
</ApolloProvider>
import { gql, graphql } from 'react-apollo'
const queryName = gql`
query {
allUsers {
id
name
}
}`
We need to use graphql() function to connet component with GraphQL data:
const ComponentWithData = graphql(queryName)(ComponentName)
If we are using Redux we just pass to connect
connected with GraphQL component:
export default connect(mapStateTopProps)(ComponentWithData)
Now we can use fetched data in connected component via props.data for example:
props.data.allUsers
We can (should) also use data
field loading
and error
to check if data is loaded or if we got some errors. For example we can write:
if(data.loading){
return <div>LOADING</div>
}
before we want use fetched data to omit asking for undefined data errors.
const productInfo = gql`
query {
allProducts {
id
name
price
category {
name
}
}
}`
Note that if our type name is Product
to call for all we write allProducts
const productDetails = gql`
query ProductQuery($id: ID!){
Product(id: $id) {
id
name
price
desc
category {
name
}
}
}`
const ProductDetailsData = graphql(productDetails, {
options: (ownProps) => ({
variables: {
id: ownProps.match.params.id
}
})
})(ProductDetails)