Skip to content

Instantly share code, notes, and snippets.

@dabit3 dabit3/App.js
Last active Nov 6, 2018

Embed
What would you like to do?
Creating a mutation in an AWS AppSync GraphQL API with AWS Amplify
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { API, graphqlOperation } from 'aws-amplify'
import { listRestaurants } from './graphql/queries'
import { createRestaurant } from './graphql/mutations'
class App extends Component {
state = { name: '', description: '', restaurants: [] }
async componentDidMount() {
try {
const apiData = await API.graphql(graphqlOperation(listRestaurants))
const restaurants = apiData.data.listRestaurants.items
this.setState({ restaurants })
} catch (err) {
console.log('error: ', err)
}
}
onChange = e => {
this.setState({ [e.target.name]: e.target.value })
}
createRestaurant = async () => {
const { name, description } = this.state
if (name === '' || description === '') return
try {
const restaurant = { name, description }
const restaurants = [...this.state.restaurants, restaurant]
this.setState({ restaurants, name: '', description: '' })
await API.graphql(graphqlOperation(createRestaurant, {input: restaurant}))
console.log('restaurant successfully created!')
} catch (err) {
console.log('error: ', err)
}
}
render() {
return (
<div className="App">
<div style={styles.inputContainer}>
<input
name='name'
placeholder='restaurant name'
onChange={this.onChange}
value={this.state.name}
style={styles.input}
/>
<input
name='description'
placeholder='restaurant description'
onChange={this.onChange}
value={this.state.description}
style={styles.input}
/>
</div>
<button
style={styles.button}
onClick={this.createRestaurant}
>Create Restaurant</button>
{
this.state.restaurants.map((rest, i) => (
<div key={i} style={styles.item}>
<p style={styles.name}>{rest.name}</p>
<p style={styles.description}>{rest.description}</p>
</div>
))
}
</div>
);
}
}
const styles = {
inputContainer: {
margin: '0 auto', display: 'flex', flexDirection: 'column', width: 300
},
button: {
border: 'none', backgroundColor: '#ddd', padding: '10px 30px'
},
input: {
fontSize: 18,
border: 'none',
margin: 10,
height: 35,
backgroundColor: "#ddd",
padding: 8
},
item: {
padding: 10,
borderBottom: '2px solid #ddd'
},
name: { fontSize: 22 },
description: { color: 'rgba(0, 0, 0, .45)' }
}
export default App
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.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.