Skip to content

Instantly share code, notes, and snippets.

@slmyers
Last active August 12, 2018 03:11
Show Gist options
  • Save slmyers/151d2da5b0f3c953d53e35e75c376dd8 to your computer and use it in GitHub Desktop.
Save slmyers/151d2da5b0f3c953d53e35e75c376dd8 to your computer and use it in GitHub Desktop.
Apollo client link example
import gql from 'graphql-tag';
export const GET_MESSAGES = gql`{
messages @client {
id
content
}
}
`;
export const ADD_MESSAGE = gql`
mutation AddMessage($content: String!, $author: String!) {
addMessage(content: $content, author: $author) @client
}
`;
import React, { Component } from "react"
import logo from '../logo.svg';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Avatar from '@material-ui/core/Avatar';
import { GET_MESSAGES } from "../GraphQL"
import { Query } from 'react-apollo';
export default class extends Component {
render(){
const { classes, scrollRef, animateScroll } = this.props;
return (
<div className={classes.incoming} ref={scrollRef}>
<Query query={GET_MESSAGES} onCompleted={() => animateScroll(scrollRef)}>
{({data: { messages } }) => (
<div style={{height: "90%", width: "90%"}}>
{messages.map( ({ author, content, id }, index) => (
<ListItem key={id} className={classes.message}>
<Avatar alt="Random Image" src={logo} />
<ListItemText primary={content} />
</ListItem>
))}
</div>
)}
</Query>
</div>
)
}
}
import React, { Component } from "react";
import TextField from '@material-ui/core/TextField';
import { withStyles } from '@material-ui/core/styles';
import AutoScroll from "./AutoScroll"
import Button from '@material-ui/core/Button';
import classes from "./classes"
import IncomingMessages from "./IncomingMessage"
import { ADD_MESSAGE } from "../GraphQL"
import { Mutation } from 'react-apollo';
@withStyles(classes)
export default class extends Component {
state = { draft: "" };
handleChange = ({ target: { value }}) => this.setState({ draft: value });
renderOutgoing = (classes=this.props.classes, handleChange=this.handleChange) => (
<Mutation mutation={ADD_MESSAGE}
variables={{ author: "YOU", content: this.state.draft }}
onCompleted={() => this.setState({ draft: "" })}>
{addMessage => (
<form
className={classes.outgoing}
onSubmit={(event) => {
event.preventDefault();
if (this.state.draft) {
addMessage()
}
}}>
<TextField
style={{flex: 1}}
placeholder="Type a message."
onChange={handleChange}
margin="normal"
value={this.state.draft}
/>
<Button type={"submit"}>Send</Button>
</form>
)}
</Mutation>
);
render() {
const { classes: { root }, classes } = this.props;
return (
<section className={root}>
<AutoScroll>
{(scrollRef, animateScroll) => (
<IncomingMessages scrollRef={scrollRef} animateScroll={animateScroll} classes={classes} />
)}
</AutoScroll>
{this.renderOutgoing()}
</section>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment