From e80374042adffc2a0843771c6aa8160b50e3061f Mon Sep 17 00:00:00 2001 From: Emanuele Paolini Date: Fri, 13 Oct 2023 09:42:49 +0200 Subject: [PATCH] refactoring * unificate viste EditExam e NewExam --- api/controllers/ModelController.js | 9 ++- frontend/src/components/NavBar.tsx | 1 - frontend/src/pages/ExamPage.js | 117 +++++++++-------------------- frontend/src/pages/ExamsPage.js | 2 +- frontend/src/pages/SinglePage.js | 1 - 5 files changed, 44 insertions(+), 86 deletions(-) diff --git a/api/controllers/ModelController.js b/api/controllers/ModelController.js index 54871796..abc88489 100644 --- a/api/controllers/ModelController.js +++ b/api/controllers/ModelController.js @@ -123,9 +123,12 @@ const ModelController = { view: async (Model, id, { populate } = {}) => { try { - const obj = (id === '__new__') ? new Model() : await Model.findById(id) - if (populate !== undefined) return await obj.populate(populate) - else return obj + const empty = id === '__new__' + let obj = empty ? new Model() : await Model.findById(id) + if (populate !== undefined) obj = await obj.populate(populate) + obj = obj.toObject() + if (empty) obj._id = undefined + return obj } catch(err) { console.log(`not found ${id}`) throw new NotFoundError() diff --git a/frontend/src/components/NavBar.tsx b/frontend/src/components/NavBar.tsx index 41987f85..c6a3c7c5 100644 --- a/frontend/src/components/NavBar.tsx +++ b/frontend/src/components/NavBar.tsx @@ -1,5 +1,4 @@ import React from 'react' -import { stringify } from "querystring" import { Link } from "react-router-dom" import { useEngine } from '../modules/engine' diff --git a/frontend/src/pages/ExamPage.js b/frontend/src/pages/ExamPage.js index 3ec7caf8..db163371 100644 --- a/frontend/src/pages/ExamPage.js +++ b/frontend/src/pages/ExamPage.js @@ -1,6 +1,6 @@ 'use strict'; -import React, { useEffect, useState } from 'react' +import React, { useState } from 'react' import { Link, useParams, useNavigate } from "react-router-dom" import Form from 'react-bootstrap/Form' import Button from 'react-bootstrap/Button' @@ -13,19 +13,12 @@ import LoadingMessage from '../components/LoadingMessage' import Card from '../components/Card' import Group from '../components/Group' -function ExamForm({ submit, exam, isEdit }) { - const [code, setCode] = useState(exam.code) - const [name, setName] = useState(exam.name) - const [sector, setSector] = useState(exam.sector) - const [credits, setCredits] = useState(exam.credits) - const [tags, setTags] = useState(exam.tags) - const [notes, setNotes] = useState(exam.notes || '') - +function ExamForm({ mutate, exam }) { + const [data, setData] = useState(exam) const [validation, setValidation] = useState({}) - - function onSubmit() { - submit({ code, name, sector, credits, tags, notes }, setValidation) - } + const isEdit = exam._id !== undefined + const engine = useEngine() + const navigate = useNavigate() return <>

{isEdit ? "Modifica esame" : "Aggiungi esame"}

@@ -37,40 +30,40 @@ function ExamForm({ submit, exam, isEdit }) { label="Codice" type="text" maxLength="6" - value={code} - onChange={e => setCode(e.target.value)} + value={data.code || ''} + onChange={setter("code")} /> setName(e.target.value)} + value={data.name || ''} + onChange={setter("name")} /> setSector(e.target.value)} + value={data.sector || ''} + onChange={setter("sector")} /> setCredits(e.target.value)} + value={data.credits || ''} + onChange={setter("credits")} /> setTags(e.target.value.split(", ").map(tag => tag.trim()))} + value={(data.tags || []).join(", ")} + onChange={e => setData(data => ({...data, tags: e.target.value.split(", ").map(tag => tag.trim())}))} /> Questo messaggio viene mostrato quando lo studente seleziona l'esame nel piano di studi. @@ -80,48 +73,31 @@ function ExamForm({ submit, exam, isEdit }) { config={{ toolbar: ['undo', 'redo', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList'] }} - data={notes} + data={data.notes || ''} onChange={(event, editor) => { - const data = editor.getData() - setNotes(data) - console.log({ event, editor, data }) + const notes = editor.getData() + setData(data => ({...data, notes})) }} /> - - + -} - -export function AddExamPage() { - const navigate = useNavigate() - const engine = useEngine() - const poster = usePost(Exam) - const emptyExam = { - code: '', - name: '', - sector: '', - credits: 0, - tags: [], - notes: '' - } - - function submit(data, setErrors) { - poster.mutate( - data, + function submit() { + mutate(data, { onSuccess: (res) => { - const newId = res.data - engine.flashSuccess("Esame aggiunto con successo") - navigate(`/exams/${newId}`) + engine.flashSuccess(isEdit + ? "Esame aggiornato con successo" + : "Esame aggiunto con successo") + const id = isEdit ? exam._id : res.data + navigate(`/exams/${id}`) }, - onError: async (err) => { - console.log(`error: ${err} ${err.code}`) - if (err.response && err.response.status === 422) { - setErrors(err.response.data.issues) + onError: (err) => { + if (err.response?.status === 422) { + setValidation(err.response.data.issues) } else { engine.flashError(`${err}`) } @@ -130,42 +106,23 @@ export function AddExamPage() { ) } - return + function setter(field) { + return e => setData(data => ({...data, [field]: e.target.value})) + } } export function EditExamPage() { - const navigate = useNavigate(); - const engine = useEngine() - const { id } = useParams() + const isNew = id === '__new__' const query = useGet(Exam, id) const updater = usePatch(Exam, id) - - function submit(data, setErrors) { - updater.mutate( - data, - { - onSuccess: () => { - engine.flashSuccess("Esame aggiornato con successo") - navigate(`/exams/${id}`) - }, - onError: (err) => { - if (err.response?.status === 422) { - setErrors(err.response.data.issues) - } else { - engine.flashError(`${err}`) - } - } - } - ) - } + const poster = usePost(Exam) + const mutate = isNew ? poster.mutate : updater.mutate if (query.isLoading) return caricamento... if (query.isError) return
Errore: {query.error.message}
- const exam = query.data - - return + return } export default function ExamPage() { diff --git a/frontend/src/pages/ExamsPage.js b/frontend/src/pages/ExamsPage.js index b94d5a6b..e956df1c 100644 --- a/frontend/src/pages/ExamsPage.js +++ b/frontend/src/pages/ExamsPage.js @@ -20,7 +20,7 @@ export default function ExamsPage() { - + Aggiungi esame diff --git a/frontend/src/pages/SinglePage.js b/frontend/src/pages/SinglePage.js index bc8254b7..bcbab1c2 100644 --- a/frontend/src/pages/SinglePage.js +++ b/frontend/src/pages/SinglePage.js @@ -76,7 +76,6 @@ function SinglePageInternal () { }/> } /> }/> - } /> }/> }/> }/>