Skip to content

Instantly share code, notes, and snippets.

@khola
Created April 12, 2019 09:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khola/0ea5b58068f3c7920767a02e9d530bc4 to your computer and use it in GitHub Desktop.
Save khola/0ea5b58068f3c7920767a02e9d530bc4 to your computer and use it in GitHub Desktop.
import React, { Component } from "react";
import Amplify, { API, graphqlOperation, Auth } from "aws-amplify";
import { withAuthenticator } from "aws-amplify-react";
import { createMessage } from "./graphql/mutations";
import { listMessages } from "./graphql/queries";
import { onCreateMessage } from "./graphql/subscriptions";
import config from "./aws-exports";
Amplify.configure(config);
class App extends Component {
state = { messages: [], input: "" };
onInput = e => {
this.setState({ input: e.target.value });
};
onSubmit = e => {
e.preventDefault();
Auth.currentAuthenticatedUser().then(user => {
const { username: nick } = user;
API.graphql(
graphqlOperation(createMessage, {
input: { content: this.state.input, nick, createdAt: 0 }
})
)
.then(e => {
this.setState({ input: "" });
console.log(e);
})
.catch(e => console.log(e));
});
};
componentDidMount() {
API.graphql(graphqlOperation(listMessages, { limit: 100 }))
.then(e => this.setState({ messages: e.data.listMessages.items }))
.catch(e => this.setState({ messages: e.data.listMessages.items }));
const subscription = API.graphql(
graphqlOperation(onCreateMessage)
).subscribe({
next: response => {
console.log(response);
this.setState({
messages: [
...this.state.messages,
response.value.data.onCreateMessage
]
});
}
});
}
render() {
const { messages, input } = this.state;
return (
<div>
{messages.map(msg => (
<p>
{msg.nick} said: {msg.content}
</p>
))}
<hr />
<input type="text" value={input} onChange={this.onInput} />
<button onClick={this.onSubmit}>Submit</button>
</div>
);
}
}
export default withAuthenticator(App, { includeGreetings: true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment