Rev 6392 | Rev 6396 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useState, useEffect } from 'react'
import { axios } from '../../../utils'
import { useForm } from 'react-hook-form'
import { connect } from 'react-redux'
import { addNotification } from '../../../redux/notification/notification.actions'
import styles from './survey.module.scss'
const SurveyForm = ({
question,
answers = [],
active,
time,
voteUrl,
addNotification,
}) => {
const [isActive, setIsActive] = useState(true)
const { register, handleSubmit } = useForm()
const sendVote = handleSubmit((data) => {
setIsActive(!isActive)
const formData = new FormData()
console.log(data)
formData.append('vote', data.vote)
axios
.post(voteUrl, formData)
.then(({ data: response }) => {
const { success, data } = response
if (!success) {
addNotification({ style: 'danger', msg: `Error: ${data}` })
setIsActive(!isActive)
return
}
addNotification({ style: 'success', msg: data })
})
.catch((err) => {
addNotification({ style: 'danger', msg: `Error: ${err}` })
throw new Error(err)
})
})
useEffect(() => {
setIsActive(Boolean(active))
}, [active])
return (
<form onChange={sendVote} className={styles.survey_form}>
<h3>{question}</h3>
{answers.map(
(option, index) =>
option && (
<div className={styles.survey_input} key={index}>
<input
type="radio"
name="vote"
id={`vote-${index + 1}`}
disabled={!isActive}
ref={register({ required: true })}
value={index + 1}
/>
<label htmlFor={`vote-${index + 1}`}>{option}</label>
</div>
)
)}
</form>
)
}
const mapDispatchToProps = {
addNotification: (notification) => addNotification(notification),
}
export default connect(null, mapDispatchToProps)(SurveyForm)