Rev 4395 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
/* eslint-disable react/prop-types */
import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { axios } from "../../../utils";
import { connect } from "react-redux";
import { addNotification } from "../../../redux/notification/notification.actions";
// Components
import Spinner from "../../../shared/loading-spinner/Spinner";
import SwitchInput from "../shared/switch-input/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.map(({ input_name, value }) => {
if (value) return 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))
}, []);
return (
<div className="acc-setting">
<h3>Privacidad</h3>
<form onSubmit={handleSubmit(handleOnSubmit)}>
{loading
? <Spinner />
: 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">
Guardar
</button>
</form>
</div>
);
};
const mapDispatchToProps = {
addNotification: (notification) => addNotification(notification),
};
export default connect(null, mapDispatchToProps)(Privacy);