stacker.news/components/reply.js

70 lines
1.9 KiB
JavaScript
Raw Normal View History

2021-04-14 23:56:29 +00:00
import { Form, Input, SubmitButton } from '../components/form'
import * as Yup from 'yup'
import { gql, useMutation } from '@apollo/client'
import styles from './reply.module.css'
2021-04-22 22:14:32 +00:00
import { COMMENTS } from '../fragments/comments'
2021-04-14 23:56:29 +00:00
export const CommentSchema = Yup.object({
text: Yup.string().required('required').trim()
})
2021-04-18 18:50:04 +00:00
export default function Reply ({ parentId, onSuccess, cacheId }) {
2021-04-14 23:56:29 +00:00
const [createComment] = useMutation(
gql`
2021-04-17 18:15:18 +00:00
${COMMENTS}
2021-04-14 23:56:29 +00:00
mutation createComment($text: String!, $parentId: ID!) {
createComment(text: $text, parentId: $parentId) {
2021-04-17 18:15:18 +00:00
...CommentFields
comments {
...CommentsRecursive
}
2021-04-14 23:56:29 +00:00
}
2021-04-17 18:15:18 +00:00
}`, {
update (cache, { data: { createComment } }) {
cache.modify({
2021-04-18 18:50:04 +00:00
id: cacheId || `Item:${parentId}`,
2021-04-17 18:15:18 +00:00
fields: {
comments (existingCommentRefs = [], { readField }) {
const newCommentRef = cache.writeFragment({
data: createComment,
fragment: COMMENTS,
fragmentName: 'CommentsRecursive'
})
return [newCommentRef, ...existingCommentRefs]
}
}
})
}
}
2021-04-14 23:56:29 +00:00
)
return (
<div className={styles.reply}>
<Form
initial={{
text: ''
}}
schema={CommentSchema}
2021-04-18 18:50:04 +00:00
onSubmit={async (values, { resetForm }) => {
const { error } = await createComment({ variables: { ...values, parentId } })
2021-04-14 23:56:29 +00:00
if (error) {
throw new Error({ message: error.toString() })
}
2021-04-18 18:50:04 +00:00
resetForm({ text: '' })
if (onSuccess) {
onSuccess()
}
2021-04-14 23:56:29 +00:00
}}
>
<Input
name='text'
as='textarea'
rows={4}
required
/>
<SubmitButton variant='secondary' className='mt-1'>reply</SubmitButton>
</Form>
</div>
)
}