Rev 6807 | AutorÃa | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useState } from 'react'
import { Button, Modal } from 'react-bootstrap'
import { axios } from '../../utils'
import { useForm } from 'react-hook-form'
import { useDispatch, useSelector } from 'react-redux'
import { addNotification } from '../../redux/notification/notification.actions'
import Spinner from '../UI/Spinner'
import TagsInput from '../../../shared/tags-input/TagsInput'
import useFetchHelper from '../../hooks/useFetchHelper'
const HobbiesModal = ({
show = false,
userId = '',
userHobbies = [],
onClose = () => {},
onComplete = () => {},
}) => {
const [modalLoading, setModalLoading] = useState(false)
const { data: hobbies } = useFetchHelper('hobbies')
const labels = useSelector(({ intl }) => intl.labels)
const dispatch = useDispatch()
const { register, handleSubmit, setValue } = useForm()
const handleTagsChange = (tags) => {
setValue('hobbiesAndInterests', tags)
}
const onSubmitHandler = async ({ hobbiesAndInterests }) => {
setModalLoading(true)
const formData = new FormData()
hobbiesAndInterests.map((language) =>
formData.append('hobbies_and_interests[]', language.value)
)
axios
.post(`/profile/my-profiles/hobby-and-interest/${userId}`, formData)
.then(({ data: response }) => {
const { data, success } = response
if (!success) {
const errorMessage = data.hobbies_and_interests[0]
dispatch(addNotification({ style: 'danger', msg: errorMessage }))
return
}
onComplete(hobbiesAndInterests)
dispatch(
addNotification({ style: 'success', msg: 'Registro actualizado' })
)
onClose()
})
.catch((error) => {
dispatch(addNotification({ style: 'danger', msg: error }))
throw new Error(error)
})
.finally(() => setModalLoading(false))
}
useEffect(() => {
register('hobbiesAndInterests')
}, [])
useEffect(() => {
show
? setValue('hobbiesAndInterests', userHobbies)
: setValue('hobbiesAndInterests', [''])
}, [show])
return (
<Modal show={show} onHide={onClose}>
<Modal.Header closeButton>
<Modal.Title>{labels.hobbies_and_interests}</Modal.Title>
</Modal.Header>
<form onSubmit={handleSubmit(onSubmitHandler)}>
<Modal.Body>
<div className="form-group">
<TagsInput
suggestions={hobbies}
settedTags={userHobbies}
onChange={handleTagsChange}
/>
</div>
</Modal.Body>
<Modal.Footer>
<Button size="sm" type="submit">
{labels.accept}
</Button>
<Button size="sm" variant="danger" onClick={onClose}>
{labels.cancel}
</Button>
</Modal.Footer>
</form>
{modalLoading && <Spinner />}
</Modal>
)
}
export default HobbiesModal