Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement