Generateurv2/frontend/components/room/ParcoursEdit.jsx
2022-05-18 10:15:54 +02:00

112 lines
2.7 KiB
JavaScript

import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { getExos, getTags } from "../../requests/requests.exos.js";
import { editParcours, getParcoursInfos } from "../../requests/requests.room.js";
import { isBrowser } from "../../utils/utils.js";
import SelectExo from "../pdf_gen/selectExo.jsx";
export default function ParcoursEdit({
parcours_id,
room_code,
user
}) {
const [parcours, setParcours] = useState();
const router = useRouter()
const [options, setOptions] = useState({name: '', timer: 0})
const [selected, setSelected] = useState([]);
const [empty, setEmpty] = useState(false);
const [exosList, setExos] = useState([]);
useEffect(() => {
if (!parcours) {
console.log("parcours", parcours);
getParcoursInfos(parcours_id, user.code)
.then((res) => {
setSelected([...res.exercices.map((ex)=>{
return ex.id_code
})])
setOptions({name: res.name, timer: res.timer})
})
.catch((err) => {
router.push({ pathname: "/room/" + room_code });
});
}
}, []);
useEffect(() => {
getExos().then((exos) => {
setExos([
...exos.map((d) => {
return { ...d, numberInExo: 10, numberOfExo: 1 };
}),
]);
});
return () => {
setExos([]);
};
}, []);
const [tags, setTags] = useState();
useEffect(() => {
console.log("test");
getTags().then((tags) => {
setTags([...tags]);
});
return () => {
setTags([]);
};
}, []);
return (
<div>
<SelectExo
exos={exosList}
tagsData={tags}
selected={selected}
select={setSelected}
emptyError={empty}
setExos={setExos}
/>
<input
type="text"
placeholder="Name"
value={options.name}
onChange={(e) => {
setOptions({ ...options, name: e.target.value });
}}
/>
<input
type="number"
placeholder="Timer (minutes)"
value={options.timer}
onChange={(e) => {
setOptions({ ...options, timer: parseInt(e.target.value) });
}}
/>
<button onClick={()=>{
if (isBrowser) {
editParcours({
...options,
exos: exosList
.filter((e) => {
return selected.includes(e.id_code);
})
.map((ee) => {
return { id_code: ee.id_code, number: ee.numberInExo };
}),
id_code: parcours_id,
code: user.code,
}).then((r) => {
router.push({
pathname: "/room/" + room_code + "/" + r.id_code,
});
});
}
}}>Save</button>
</div>
);
}