Rev 1437 | AutorÃa | Ultima modificación | Ver Log |
import React, { useState } from 'react'import { useDispatch } from 'react-redux'import { useForm } from 'react-hook-form'import { axios } from '../../utils'import { addNotification } from '../../redux/notification/notification.actions'import useFetchHelper from '../../hooks/useFetchHelper'import Modal from 'components/UI/modal/Modal'import Spinner from 'components/UI/Spinner'import FormErrorFeedback from 'components/UI/form/FormErrorFeedback'const AddGroupModal = ({ show, onHide, fetchGroups }) => {const [loading, setLoading] = useState(false)const { data: groupTypes } = useFetchHelper('group-types')const { data: industries } = useFetchHelper('industries')const dispatch = useDispatch()const { register, handleSubmit, errors, setError } = useForm()const onSubmit = handleSubmit((data) => {setLoading(true)const formData = new FormData()Object.entries(data).forEach(([key, value]) => formData.append(key, value))axios.post(`/group/my-groups/add`, formData).then(({ data: responseData }) => {const { data, success } = responseDataif (!success) {const errorMessage = dataconst isObject = typeof errorMessage === 'object'if (isObject) {Object.entries(errorMessage).map(([key, value]) =>setError(key, {type: 'manual',message: Array.isArray(value) ? value[0] : value}))return}throw new Error(errorMessage)}fetchGroups()onHide()}).catch((err) => {dispatch(addNotification({ style: 'danger', msg: err.message }))}).finally(() => setLoading(false))})return (<Modal title='Nuevo Grupo' show={show} onClose={onHide} onAccept={onSubmit}><div className='form-group'><inputtype='text'name='name'id='name'placeholder='Nombre del grupo'ref={register({required: 'Por favor ingrese el nombre del grupo'})}/>{errors.name && (<FormErrorFeedback>{errors.name.message}</FormErrorFeedback>)}</div><div className='form-group'><selectname='type_id'id='type_id'defaultValue=''ref={register({required: 'Por favor eliga un tipo'})}><option value='' hidden>Tipo</option>{groupTypes.map(({ name, value }) => (<option value={value} key={name}>{name}</option>))}</select>{errors.type_id && (<FormErrorFeedback>{errors.type_id.message}</FormErrorFeedback>)}</div><div className='form-group'><selectname='industry_id'id='industry_id'defaultValue=''ref={register({required: 'Por favor eliga una industria'})}><option value='' hidden>Industria</option>{industries.map(({ name, value }) => (<option value={value} key={value}>{name}</option>))}</select>{errors.industry_id && (<FormErrorFeedback>{errors.industry_id.message}</FormErrorFeedback>)}</div>{loading && <Spinner />}</Modal>)}export default AddGroupModal