Skip to content

Instantly share code, notes, and snippets.

@dabit3
Last active April 5, 2022 05:09
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dabit3/dc48bad13bdc92419f47a9509a95c538 to your computer and use it in GitHub Desktop.
Save dabit3/dc48bad13bdc92419f47a9509a95c538 to your computer and use it in GitHub Desktop.
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