Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6402 | Rev 6407 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useState } 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'
import { updateFeed } from '../../../redux/feed/feed.actions'

const SurveyForm = ({
  question,
  answers = [],
  active,
  time,
  resultType,
  voteUrl,
  addNotification, // Redux action
  updateFeed, // Redux action
}) => {
  const [isActive, setIsActive] = useState(Boolean(active))
  const { register, handleSubmit } = useForm()

  const sendVote = handleSubmit(({ vote }) => {
    setIsActive(false)
    const formData = new FormData()

    formData.append('vote', vote)

    axios
      .post(voteUrl, formData)
      .then(({ data: response }) => {
        const { success, data } = response
        if (!success) {
          addNotification({ style: 'danger', msg: `Error: ${data}` })
          setIsActive(true)
        }

        updateFeed({ feed: data, uuid: data.uuid })
      })
      .catch((err) => {
        addNotification({ style: 'danger', msg: `Error: ${err}` })
        setIsActive(true)
        throw new Error(err)
      })
  })

  return (
    <form onChange={sendVote} className={styles.survey_form}>
      <h3>{question}</h3>
      {resultType === 'pu' && <p>El autor puede ver tu voto</p>}
      {resultType === 'pr' && <p>Tu voto es privado</p>}
      {answers.map(
        (option, index) =>
          option && (
            <div
              className={
                isActive
                  ? styles.survey_input
                  : styles.survey_input + ' ' + styles.disabled
              }
              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),
  updateFeed: (payload) => updateFeed(payload),
}

export default connect(null, mapDispatchToProps)(SurveyForm)