Skip to content

Instantly share code, notes, and snippets.

@Jeyloh
Last active March 11, 2019 22:12
Show Gist options
  • Save Jeyloh/9fecf6b5d67c9c7b9c0aac72958969e4 to your computer and use it in GitHub Desktop.
Save Jeyloh/9fecf6b5d67c9c7b9c0aac72958969e4 to your computer and use it in GitHub Desktop.
import React from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, Button } from 'react-native';
import { API, graphqlOperation } from 'aws-amplify';
import * as queries from "./graphql/queries";
import * as mutations from "./graphql/mutations";
import * as subscriptions from "./graphql/subscriptions";
export default class Root extends React.Component {
constructor(props) {
super(props);
this.state = {
quotes: [],
input: ""
}
}
componentDidMount() {
this.getQuotesList();
API.graphql(graphqlOperation(subscriptions.onCreateQuote)).subscribe({
next: (data) => {
console.log(data);
const addedQuote = data.value.data.onCreateQuote;
this.setState({ quotes: [addedQuote, ...this.state.quotes] });
}
});
API.graphql(graphqlOperation(subscriptions.onDeleteQuote)).subscribe({
next: (data) => {
console.log(data);
const removedQuote = data.value.data.onDeleteQuote;
const updatedList = this.state.quotes.filter((quote => {
return quote.id !== removedQuote.id;
}))
this.setState({ quotes: updatedList });
}
});
}
getQuotesList = async () => {
try {
const response = await API.graphql(graphqlOperation(queries.listQuotes));
this.setState({ quotes: response.data.listQuotes.items });
} catch (err) {
console.error(err);
}
}
addQuote = async () => {
try {
const quoteObj = {
quote: this.state.input,
}
await API.graphql(graphqlOperation(mutations.createQuote, { input: quoteObj }))
this.setState({ input: "" });
} catch (err) {
console.error(err);
}
}
deleteQuote = async (id) => {
try {
await API.graphql(graphqlOperation(mutations.deleteQuote, { input: { id: id } }))
} catch (err) {
console.error(err);
}
}
render() {
return (
<View style={styles.container}>
<TextInput
style={{ height: 40 }}
value={this.state.input}
placeholder="Type a quote!"
onChangeText={(text) => this.setState({ input: text })}
/>
<Button title="Add Quote" onPress={this.addQuote} />
<FlatList
data={this.state.quotes}
renderItem={({ item }) => (
<View key={item.id}>
<Text style={styles.item}>"{item.quote}"</Text>
<Text style={styles.item}>- {item.owner}</Text>
<View style={{ width: 150 }}>
<Button title="Delete Quote" color="#ffa500" onPress={() => this.deleteQuote(item.id)} />
</View>
</View>
)}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22,
marginLeft: 20,
marginRight: 20
},
item: {
padding: 10,
fontSize: 18,
height: 44,
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment