Reputation: 2543
I see a lot of people using redux and mobx with Apollo client. However, after reading the docs it mentions that you perhaps do not need this:
Ideally, we would like the Apollo cache to be the single source of truth for all data in our client application.
How would one share global state in Apollo client? And is mobx, or redux, really necessary?
Upvotes: 1
Views: 473
Reputation: 24130
No mobx or redux is not necessary at all.
Apollo-link-state is sufficient enough to manage the local app state and be the single source of truth for your data.
import {withClientState} from 'apollo-link-state'
import typeDefs from '../schema/schema'
import resolvers from '../resolvers'
const initialState = {
intialData: [],
myData: {
__typename: 'MyDataType',
},
}
async function getLocalLinkState(cache) {
const stateLink = withClientState({
cache,
defaults: initialState,
resolvers: resolvers,
typeDefs
})
return stateLink
}
export default getLocalLinkState
Basically you create similar typedefs(not mandatory) and resolvers same as your graphql server.
So your initialState
will be shared as global state which you can read or write to using client side Queries and client side mutations.
These Client side Queries and mutations will be resolved by client side resolvers not server side resolvers (If you have used @client )
Client Side Query:
const query = gql`
{
counter @client
}
`;
Examples of Mutation Resolvers
decrementCounter: (_, params, { cache }) => {
const { counter } = cache.readQuery({ query });
const nextCounter = counter - 1;
const data = {
counter: nextCounter,
};
cache.writeData({ data });
return nextCounter;
},
incrementCounter: (_, params, { cache }) => {
const { counter } = cache.readQuery({ query });
const nextCounter = counter + 1;
const data = {
counter: nextCounter,
};
cache.writeData({ data });
return nextCounter;
},
Any components consuming local app state will be updated if any change occurs to part of app state they are consuming.
Upvotes: 3