// from: apollographql/apollo-link-state#10 (comment)
This puts my examples for a string and array variable to this much nicer code:
Initiate apollo in index.js:
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloProvider } from 'react-apollo'
import { concat } from 'apollo-link'
import localStateLink from './localStateLink'
const httpLink = createHttpLink({ uri: 'http://localhost:5000/graphql' })
const client = new ApolloClient({
link: concat(localStateLink, httpLink),
cache: new InMemoryCache(),
})localStateLink.js:
import { withClientState } from 'apollo-link-state'
import activeNodeArrayGql from './modules/activeNodeArrayGql'
import activeObjectIdGql from './modules/activeObjectIdGql'
export default withClientState({
Query: {
// provide initial state
activeNodeArray: () => [],
activeObjectId: () => null,
},
Mutation: {
// update values in the store on mutations
setActiveNodeArray: (_, { value }, { cache }) => {
cache.writeQuery({
query: activeNodeArrayGql,
data: { activeNodeArray: value },
})
return value
},
setActiveObjectId: (_, { value }, { cache }) => {
cache.writeQuery({
query: activeObjectIdGql,
data: { activeObjectId: value },
})
return value
},
},
})activeNodeArrayGql.js:
import gql from 'graphql-tag'
export default gql`
query activeNodeArrayQuery {
activeNodeArray @client
}
`activeObjectIdGql.js:
import gql from 'graphql-tag'
export default gql`
query activeObjectIdQuery {
activeObjectId @client
}
`Fetching a store variable in a component:
import { graphql } from 'react-apollo'
import compose from 'recompose/compose'
... other imports
import activeNodeArrayGql from '../modules/activeNodeArrayGql'
const activeNodeArrayData = graphql(activeNodeArrayGql, {
name: 'activeNodeArrayData',
})
const enhance = compose(activeNodeArrayData, others)
const MyAppBar = ({
activeNodeArrayData,
...others
}: {
activeNodeArrayData: Object,
...others
}) => {
const { activeNodeArray } = activeNodeArrayData
return (<div>my appbar</div>)
}
export default enhance(MyAppBar)