Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import { gql, graphql, withApollo, compose } from 'react-apollo';
  3.  
  4. class Box extends Component {
  5. state = {
  6. mutateCount: 0, // the number of times we have called mutate()
  7. subCount: 0, // the number of times we have received subscription event
  8. };
  9.  
  10. componentWillMount() {
  11. console.log('componentWillMount');
  12. if (this.props.match.params.name === 'leader') {
  13. this.interval = setInterval(() => this.handleClick(), 100);
  14. }
  15. }
  16.  
  17. componentWillUnmount() {
  18. clearInterval(this.interval);
  19. }
  20.  
  21. componentDidMount() {
  22. console.log('componentDidMount');
  23.  
  24. // setup subscription
  25. this.observer = this.props.client.subscribe({
  26. query: gql`
  27. subscription {
  28. Box {
  29. mutation
  30. node {
  31. id
  32. count
  33. }
  34. }
  35. }
  36. `,
  37. }).subscribe({
  38. next: (data) => {
  39. this.setState({ subCount: this.state.subCount + 1});
  40. console.log('s>>>', this.state.subCount, data.Box.node.count, this.state.subCount === data.Box.node.count);
  41. },
  42. error: (error) => {
  43. console.error('Subscription callback with error: ', error)
  44. },
  45. })
  46. }
  47.  
  48. handleClick() {
  49. this.setState({ mutateCount: this.state.mutateCount + 1 });
  50.  
  51. this.props.mutate({
  52. variables: { count: this.state.mutateCount }
  53. });
  54.  
  55. console.log('m<<<', this.state.mutateCount);
  56.  
  57. // stop after 100
  58. if (this.state.mutateCount >= 100) {
  59. clearInterval(this.interval);
  60. }
  61. }
  62.  
  63. render() {
  64. if (this.props.data.loading) return null;
  65.  
  66. return (
  67. <div onClick={() => this.handleClick()} >
  68. {this.state.mutateCount}:{this.props.data.Box.count}:{this.state.subCount}
  69. </div>
  70. );
  71. }
  72. }
  73.  
  74. const BoxQuery = gql`query {
  75. Box(id: "cj5b9xytx07nd0156x9eql6zk") {
  76. id
  77. count
  78. }
  79. }`;
  80.  
  81. const BoxMutation = gql`mutation ($count: Int!) {
  82. updateBox(id: "cj5b9xytx07nd0156x9eql6zk", count: $count) {
  83. id
  84. }
  85. }`;
  86.  
  87. const BoxWithData = compose(
  88. graphql(BoxQuery),
  89. graphql(BoxMutation)
  90. )(Box);
  91.  
  92. export default withApollo(BoxWithData);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement