Created
July 16, 2020 19:09
-
-
Save gcmatheusj/0cb18f2a8e634e3bf160aff0e90fec3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useCallback } from 'react' | |
import PropTypes from 'prop-types' | |
import { useFormik } from 'formik' | |
import { useMutation } from '@apollo/react-hooks' | |
import { gql } from 'apollo-boost' | |
import { EditorState, convertToRaw } from 'draft-js' | |
import { Button, Typography } from '@material-ui/core' | |
import { useSnackbar } from '../../../../../lib/SnackbarContext' | |
import { useAccount } from '../../../../../lib/AccountContext' | |
import useStyles from './styles' | |
import Editor from '../../../../Editor-DRAFT' | |
const CREATE_DISCUSSION_ANSWER = gql` | |
mutation($accountId: String!, $input: ThreadAnswersInput!) { | |
createThreadAnswer(accountId: $accountId, input: $input) { | |
id | |
} | |
} | |
` | |
const AnswerForm = ({ threadId, refetch }) => { | |
const classes = useStyles() | |
const { id: accountId } = useAccount() | |
const { handleOpenSnackbar } = useSnackbar() | |
const [createThreadAnswer] = useMutation(CREATE_DISCUSSION_ANSWER) | |
const { values, setFieldValue, handleSubmit, resetForm } = useFormik({ | |
initialValues: { | |
body: EditorState.createEmpty() | |
}, | |
onSubmit: async (values) => { | |
const bodyState = values.body.getCurrentContent() | |
await createThreadAnswer({ | |
variables: { | |
accountId, | |
input: { | |
threadId, | |
body: JSON.stringify(convertToRaw(bodyState)) | |
} | |
} | |
}) | |
resetForm() | |
handleOpenSnackbar({ severity: 'success', message: 'Resposta criada.' }) | |
refetch() | |
} | |
}) | |
const onChange = useCallback( | |
(editorState) => { | |
setFieldValue('body', editorState) | |
}, | |
[setFieldValue] | |
) | |
return ( | |
<React.Fragment> | |
<Typography className={classes.title} variant="subtitle1"> | |
Nova Resposta | |
</Typography> | |
<form onSubmit={handleSubmit}> | |
<Editor value={values.body} onChange={onChange} height={180} /> | |
<Button | |
className={classes.button} | |
type="submit" | |
variant="contained" | |
color="primary" | |
disableElevation | |
> | |
Postar Resposta | |
</Button> | |
</form> | |
</React.Fragment> | |
) | |
} | |
AnswerForm.propTypes = { | |
threadId: PropTypes.string.isRequired, | |
refetch: PropTypes.func.isRequired | |
} | |
export default AnswerForm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment