Skip to content

Instantly share code, notes, and snippets.

@youneshenniwrites
Created December 22, 2018 10:39
Show Gist options
  • Save youneshenniwrites/d06f1eadee3247789dfa0c0d279fe263 to your computer and use it in GitHub Desktop.
Save youneshenniwrites/d06f1eadee3247789dfa0c0d279fe263 to your computer and use it in GitHub Desktop.
Functionality of the like button for the Zopher app
toggleLikePost = async (post) => {
const loggedInUser = await this.state.postOwnerId
// Get the like instance of the logged in user
const likeUserObject = await post.likes.items.filter(
obj => obj.likeOwnerId === loggedInUser
)
// If there is a like instance fire a delete action
if (likeUserObject.length !== 0) {
await this.deleteLike(likeUserObject)
return
}
// Otherwise create a like instance
await this.createLike(post)
}
createLike = async (post) => {
const postId = await post['id']
this.setState({numberLikes: 1})
const like = {
likeOwnerId: this.state.likeOwnerId,
numberLikes: this.state.numberLikes,
likeOwnerUsername: this.state.likeOwnerUsername,
id: postId,
}
try {
await API.graphql(graphqlOperation(createLike, like))
console.log('Like successfully created.', like)
await this.componentDidMount()
} catch (err) {
console.log('Error creating like.', err)
}
}
deleteLike = async (likeUserObject) => {
const likeId = await likeUserObject[0]['id']
try {
await API.graphql(graphqlOperation(deleteLike, { id: likeId }))
console.log('Like successfully deleted.')
await this.componentDidMount()
} catch (err) {
console.log('Error deleting like.', err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment