Skip to content

Instantly share code, notes, and snippets.

@rcy
Last active July 20, 2017 17:19
Show Gist options
  • Save rcy/31e0c393164ff73e6f8774b45a5c77ee to your computer and use it in GitHub Desktop.
Save rcy/31e0c393164ff73e6f8774b45a5c77ee to your computer and use it in GitHub Desktop.
component to test mutation updates and subscriptions on graphql/graphcool
import React, { Component } from 'react';
import { gql, graphql, withApollo, compose } from 'react-apollo';
class Box extends Component {
state = {
mutateCount: 0, // the number of times we have called mutate()
subCount: 0, // the number of times we have received subscription event
};
componentWillMount() {
console.log('componentWillMount');
if (this.props.match.params.name === 'leader') {
this.interval = setInterval(() => this.handleClick(), 100);
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
componentDidMount() {
console.log('componentDidMount');
// setup subscription
this.observer = this.props.client.subscribe({
query: gql`
subscription {
Box {
mutation
node {
id
count
}
}
}
`,
}).subscribe({
next: (data) => {
this.setState({ subCount: this.state.subCount + 1});
console.log('s>>>', this.state.subCount, data.Box.node.count, this.state.subCount === data.Box.node.count);
},
error: (error) => {
console.error('Subscription callback with error: ', error)
},
})
}
handleClick() {
this.setState({ mutateCount: this.state.mutateCount + 1 });
this.props.mutate({
variables: { count: this.state.mutateCount }
});
console.log('m<<<', this.state.mutateCount);
// stop after 100
if (this.state.mutateCount >= 100) {
clearInterval(this.interval);
}
}
render() {
if (this.props.data.loading) return null;
return (
<div onClick={() => this.handleClick()} >
{this.state.mutateCount}:{this.props.data.Box.count}:{this.state.subCount}
</div>
);
}
}
const BoxQuery = gql`query {
Box(id: "cj5b9xytx07nd0156x9eql6zk") {
id
count
}
}`;
const BoxMutation = gql`mutation ($count: Int!) {
updateBox(id: "cj5b9xytx07nd0156x9eql6zk", count: $count) {
id
}
}`;
const BoxWithData = compose(
graphql(BoxQuery),
graphql(BoxMutation)
)(Box);
export default withApollo(BoxWithData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment