Skip to content

Instantly share code, notes, and snippets.

@khola khola/snip2
Created Apr 12, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.