import * as React from "react"; import { graphql, MutationFunc } from "react-apollo"; import VoteButton from "./vote_button.component"; import { AddCommentFormCommentableFragment, AddCommentFormSessionFragment, CommentFragment, GetCommentsQuery, UpVoteButtonFragment, UpVoteMutation, } from "../support/schema"; interface UpVoteButtonProps { session: AddCommentFormSessionFragment & { user: any; } | null; comment: UpVoteButtonFragment; upVote?: () => void; rootCommentable: AddCommentFormCommentableFragment; orderBy: string; } export const UpVoteButton: React.SFC = ({ session, comment: { upVotes, upVoted, downVoted }, upVote, }) => { let selectedClass = ""; if (upVoted) { selectedClass = "is-vote-selected"; } else if (downVoted) { selectedClass = "is-vote-notselected"; } const userLoggedIn = session && session.user; const disabled = upVoted || downVoted; return ( ); }; const upVoteMutation = require("../mutations/up_vote.mutation.graphql"); const getCommentsQuery = require("../queries/comments.query.graphql"); const UpVoteButtonWithMutation = graphql(upVoteMutation, { props: ({ ownProps, mutate }: { ownProps: UpVoteButtonProps, mutate: MutationFunc }) => ({ upVote: () => mutate({ variables: { id: ownProps.comment.id, }, optimisticResponse: { __typename: "Mutation", comment: { __typename: "CommentMutation", upVote: { __typename: "Comment", ...ownProps.comment, upVotes: ownProps.comment.upVotes + 1, upVoted: true, }, }, }, update: (store, result: UpVoteMutation) => { const variables = { commentableId: ownProps.rootCommentable.id, commentableType: ownProps.rootCommentable.type, orderBy: ownProps.orderBy, }; const commentReducer = (comment: CommentFragment): CommentFragment => { const replies = comment.comments || []; if (comment.id === ownProps.comment.id && result.comment) { return result.comment.upVote; } return { ...comment, comments: replies.map(commentReducer), }; }; const prev = store.readQuery({ query: getCommentsQuery, variables }); store.writeQuery({ query: getCommentsQuery, data: { ...prev, commentable: { ...prev.commentable, comments: prev.commentable.comments.map(commentReducer), }, }, variables, }); }, }), }), })(UpVoteButton); export default UpVoteButtonWithMutation;