Skip to content

Instantly share code, notes, and snippets.

@Developerayo
Created June 20, 2019 09:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Developerayo/bec654e28bc9477a51267fd77682bfd0 to your computer and use it in GitHub Desktop.
Save Developerayo/bec654e28bc9477a51267fd77682bfd0 to your computer and use it in GitHub Desktop.
import {InMemoryCache} from 'apollo-cache-inmemory';
import {ApolloLink} from 'apollo-client-preset';
import {ApolloClient} from 'apollo-client';
import {withClientState} from 'apollo-link-state';
import gql from 'graphql-tag';
import {graphql} from 'react-apollo';
import compose from 'recompose/compose';
/*
Defaults
*/
const DataDefaults = {
currentDatas: [],
};
/*
GraphQL
*/
const DataQuery = gql`
query GetData {
currentDatas @client
}
`;
const clearDataQuery = gql`
mutation clearData {
clearData @client
}
`;
const addDataQuery = gql`
mutation addData($item: String) {
addData(item: $item) @client
}
`;
/*
Cache Mutations
*/
const addData = (_obj, {item}, {cache}) => {
const query = DataQuery;
// Read the Data's from the cache
const {currentDatas} = cache.readQuery({query});
// Add the item to the current Datas
const updatedDatas = currentDatas.concat(item);
// Update the cached Datas
cache.writeQuery({query, data: {currentDatas: updatedDatas}});
return null;
};
const clearData = (_obj, _args, {cache}) => {
cache.writeQuery({query: DataQuery, data: DataDefaults});
return null;
};
/*
Store
*/
// Set up Cache
const cache = new InMemoryCache();
// Set up Local State
const stateLink = withClientState({
cache,
defaults: DataDefaults,
resolvers: {
Mutation: {
addData,
clearData,
},
},
});
// Initialize the Apollo Client
const Client = new ApolloClient({
link: ApolloLink.from([
stateLink,
]),
cache: cache,
});
/*
Helpers
*/
const DataQueryHandler = {
props: ({ownProps, data: {currentDatas = []}}) => ({
...ownProps,
currentDatas,
}),
};
const withData = compose(
graphql(DataQuery, DataQueryHandler),
graphql(addDataQuery, {name: 'addDataMutation'}),
graphql(clearDataQuery, {name: 'clearDataMutation'}),
);
export {
Client,
withData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment