Rev 3432 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { connect } from 'react-redux'
import { axios } from 'utils'
import { addNotification } from '@app/redux/notification/notification.actions'
import Widget from '@components/UI/Widget'
import Spinner from '@components/UI/Spinner'
import SwitchInput from '@components/UI/SwitchInput'
const PRIVACY_OPTIONS = [
{
label: 'Mostrar en la búsqueda',
input_name: 'show_in_search',
value: false
}
]
const Privacy = ({ addNotification }) => {
const [loading, setLoading] = useState(false)
const [options, setOptions] = useState(PRIVACY_OPTIONS)
const { handleSubmit } = useForm()
const handleOnSubmit = () => {
setLoading(true)
const formData = new FormData()
options.forEach(({ input_name, value }) =>
formData.append(input_name, value ? 'y' : 'n')
)
axios
.post('/account-settings/privacy', formData)
.then(({ data: response }) => {
if (!response.success) {
typeof response.data === 'string'
? addNotification({ style: 'danger', msg: response.data })
: Object.entries(response.data).map(([key, value]) =>
addNotification({
style: 'success',
msg: `${key} error: ${value} `
})
)
}
addNotification({ style: 'success', msg: response.data })
})
.finally(() => setLoading(false))
}
const handleChecked = (value, element) => {
setOptions((prevNotifications) =>
prevNotifications.map((notification) =>
notification.input_name === element
? { ...notification, value: Boolean(value) }
: notification
)
)
}
useEffect(() => {
setLoading(true)
axios
.get('/account-settings/privacy')
.then(({ data: response }) => {
if (response.success) {
Object.entries(response.data).map(([key, value]) =>
setOptions((prevOption) =>
prevOption.map((option) =>
option.input_name === key
? { ...option, value: Boolean(value) }
: option
)
)
)
}
})
.finally(() => setLoading(false))
}, [])
if (loading) {
return <Spinner />
}
return (
<Widget>
<Widget.Header title='Privacidad' />
<Widget.Body>
<form onSubmit={handleSubmit(handleOnSubmit)}>
{options.map((option, index) => {
return (
<div className='notbat' key={index}>
<span>{option.label}</span>
<SwitchInput
isChecked={option.value}
setValue={(value) => handleChecked(value, option.input_name)}
/>
</div>
)
})}
<button type='submit' className='btn btn-primary mt-3'>
Guardar
</button>
</form>
</Widget.Body>
</Widget>
)
}
const mapDispatchToProps = {
addNotification: (notification) => addNotification(notification)
}
export default connect(null, mapDispatchToProps)(Privacy)