Rev 655 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useState } from "react";
import { Button, Form, Modal } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import { CKEditor } from "ckeditor4-react";
import { CKEDITOR_OPTIONS, axios } from "../../utils";
import { useForm } from "react-hook-form";
import { addNotification } from "../../redux/notification/notification.actions";
import Spinner from "../UI/Spinner";
import TagsInput from "../UI/TagsInput";
import FormErrorFeedback from "../UI/FormErrorFeedback";
import { styled } from "styled-components";
const TagsContainer = styled.div`
padding: 0.5rem;
border: 1px solid var(--border-primary);
border-radius: var(--border-radius);
margin-top: 1rem;
`;
const QuestionModal = ({ show, url, isEdit, onClose, onComplete }) => {
const [loading, setLoading] = useState(false);
const [questionsCategories, setQuestionsCategories] = useState([]);
const [currentCategories, setCurrentCategories] = useState([]);
const labels = useSelector(({ intl }) => intl.labels);
const dispatch = useDispatch();
const { register, handleSubmit, getValues, setValue, errors } = useForm();
const onSubmit = handleSubmit((data) => {
setLoading(true);
const formData = new FormData();
Object.entries(data).map(([key, value]) => formData.append(key, value));
axios
.post(url, formData)
.then((response) => {
const { data, success } = response.data;
if (!success) {
const errorMessage =
typeof data === "string"
? data
: "Error interno. Por favor, inténtelo de nuevo más tarde.";
dispatch(addNotification({ style: "danger", msg: errorMessage }));
return;
}
onComplete();
onClose();
})
.finally(() => setLoading(false));
});
const getCategories = () => {
axios
.get("/my-coach", {
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
const { data, success } = response.data;
if (!success) {
const errorMessage =
typeof data === "string"
? data
: "Error interno. Por favor, inténtelo de nuevo más tarde.";
dispatch(addNotification({ style: "danger", msg: errorMessage }));
return;
}
const categories = Object.entries(data.categories).map((values) => ({
name: values[1],
value: values[0],
}));
setQuestionsCategories(categories);
})
.catch((error) => {
dispatch(
addNotification({
style: "danger",
msg: "Error interno. Por favor, inténtelo de nuevo más tarde.",
})
);
throw new Error(error);
});
};
const onTagsChange = (tags) => {
const categories = tags.map((tag) => tag.value);
setValue("category_id", categories);
};
useEffect(() => {
getCategories();
register("description", { required: true });
register("category_id", { required: true });
}, []);
useEffect(() => {
if (!url || !show || !isEdit || !questionsCategories.length) return;
axios.get(url).then((response) => {
const { data, success } = response.data;
if (!success) {
const errorMessage =
typeof data === "string"
? data
: "Error interno. Por favor, inténtelo de nuevo más tarde.";
dispatch(
addNotification({
style: "danger",
msg: errorMessage,
})
);
return;
}
const categories = data.category_id.map((uuid) =>
questionsCategories.find((c) => c.value === uuid)
);
setCurrentCategories(categories);
setValue("title", data.title);
setValue("description", data.description);
});
}, [url, show, isEdit, questionsCategories]);
useEffect(() => {
if (!show) {
setCurrentCategories([]);
setValue("category_id", []);
setValue("description", "");
setValue("title", "");
}
}, [show]);
return (
<Modal show={show}>
<Modal.Header className="pb-0">
<Modal.Title>
{isEdit ? labels.edit : labels.add} {labels.question}
</Modal.Title>
</Modal.Header>
<Modal.Body>
{loading ? (
<Spinner />
) : (
<Form onSubmit={onSubmit}>
<Form.Group>
<Form.Label>{labels.title}</Form.Label>
<Form.Control
type="text"
name="title"
ref={register({ required: true })}
/>
{errors.title && (
<FormErrorFeedback>
{labels.error_field_empty}
</FormErrorFeedback>
)}
</Form.Group>
<CKEditor
onChange={(e) => setValue("description", e.editor.getData())}
onInstanceReady={(e) =>
e.editor.setData(getValues("description"))
}
config={CKEDITOR_OPTIONS}
/>
{errors.description && (
<FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
)}
<TagsContainer>
<TagsInput
suggestions={questionsCategories}
settedTags={currentCategories}
onChange={onTagsChange}
/>
</TagsContainer>
<Button className="mt-3 mr-2" variant="primary" type="submit">
{labels.accept}
</Button>
<Button className="btn-secondary mt-3" onClick={onClose}>
{labels.cancel}
</Button>
</Form>
)}
</Modal.Body>
</Modal>
);
};
export default QuestionModal;