(#16) Редактирование лекции #18

Merged
primakov merged 1 commits from feature/edit-delete-lesson into master 2024-04-02 16:21:06 +03:00
3 changed files with 195 additions and 127 deletions
Showing only changes of commit a32e55807b - Show all commits

View File

@ -78,6 +78,14 @@ export const api = createApi({
}),
invalidatesTags: ['LessonList'],
}),
updateLesson: builder.mutation<BaseResponse<Lesson>, Partial<Lesson> & Pick<Lesson, '_id'>>({
query: (data) => ({
method: 'PUT',
url: `/lesson/${data._id}`,
body: data,
}),
invalidatesTags: ['LessonList'],
}),
deleteLesson: builder.mutation<null, string>({
query: (lessonId) => ({
url: `/lesson/${lessonId}`,

View File

@ -46,50 +46,149 @@ import {
} from '@chakra-ui/react'
import { AddIcon, EditIcon } from '@chakra-ui/icons'
import { ErrorSpan, BreadcrumbsWrapper } from './style'
import { useAppSelector } from '../__data__/store'
import { api } from '../__data__/api/api'
import { isTeacher } from '../utils/user'
import { qrCode } from '../assets'
import { Lesson } from '../__data__/model'
import { ErrorSpan, BreadcrumbsWrapper } from './style'
interface NewLessonForm {
name: string
date: string
}
interface LessonFormProps {
lesson?: Partial<Lesson>
isLoading: boolean
onCancel: () => void
onSubmit: (lesson: Lesson) => void
error?: string
}
const LessonForm = ({
lesson,
isLoading,
onCancel,
onSubmit,
error,
}: LessonFormProps) => {
const {
control,
handleSubmit,
reset,
formState: { errors },
} = useForm<NewLessonForm>({
defaultValues: lesson || {
name: '',
date: '',
},
})
return (
<Card align="left">
<CardHeader display="flex">
<Heading as="h2" mt="0">
Создание лекции
</Heading>
<CloseButton
ml="auto"
onClick={() => {
reset()
onCancel()
}}
/>
</CardHeader>
<CardBody>
<form onSubmit={handleSubmit(onSubmit)}>
<VStack spacing="10" align="left">
<Controller
control={control}
name="date"
rules={{ required: 'Обязательное поле' }}
render={({ field }) => (
<FormControl>
<FormLabel>Дата</FormLabel>
<Input
{...field}
required={false}
placeholder="Укажите дату лекции"
size="md"
type="datetime-local"
/>
{errors.date ? (
<FormErrorMessage>{errors.date?.message}</FormErrorMessage>
) : (
<FormHelperText>Укажите дату и время лекции</FormHelperText>
)}
</FormControl>
)}
/>
<Controller
control={control}
name="name"
rules={{ required: 'Обязательное поле' }}
render={({ field }) => (
<FormControl isRequired isInvalid={Boolean(errors.name)}>
<FormLabel>Название новой лекции:</FormLabel>
<Input
{...field}
required={false}
placeholder="Название лекции"
size="md"
/>
{errors.name && (
<FormErrorMessage>{errors.name.message}</FormErrorMessage>
)}
</FormControl>
)}
/>
<Box mt="10">
<Button
size="lg"
type="submit"
leftIcon={<AddIcon />}
colorScheme="blue"
isLoading={isLoading}
>
Создать
</Button>
</Box>
</VStack>
{error && <ErrorSpan>{error}</ErrorSpan>}
</form>
</CardBody>
</Card>
)
}
const LessonList = () => {
const { courseId } = useParams()
const user = useAppSelector((s) => s.user)
const { data, isLoading, error } = api.useLessonListQuery(courseId)
const [createLesson, crLQuery] = api.useCreateLessonMutation()
const [deleteLesson, deletingRqst] = api.useDeleteLessonMutation()
const [updateLesson, updateLessonRqst] = api.useUpdateLessonMutation()
const [showForm, setShowForm] = useState(false)
const [lessonToDelete, setlessonToDelete] = useState<Lesson>(null)
const cancelRef = React.useRef()
const {
control,
handleSubmit,
reset,
formState: { errors },
getValues,
} = useForm<NewLessonForm>({
defaultValues: {
name: '',
date: '',
},
})
const toast = useToast()
const toastRef = useRef(null)
const createdLessonRef = useRef(null)
const [editLesson, setEditLesson] = useState<Lesson>(null)
const onSubmit = ({ name, date }) => {
const onSubmit = (lessonData) => {
toastRef.current = toast({
title: 'Отправляем',
status: 'loading',
duration: 9000,
})
createLesson({ name, courseId, date })
createdLessonRef.current = lessonData
if (editLesson) updateLesson(lessonData)
else createLesson({ courseId, ...lessonData })
}
useEffect(() => {
@ -106,27 +205,27 @@ const LessonList = () => {
toast({
status: 'warning',
duration: 9000,
render(props) {
return (
render: ({ id, ...toastProps }) => (
<Toast
{...props}
{...toastProps}
id={id}
title={
<>
<Box pb={3}>
<Text fontSize="xl">{`Удалена лекция ${lesson.name}`}</Text>
</Box>
<Button
onClick={() =>
onClick={() => {
createLesson({ courseId, ...lesson })
}
toast.close(id)
}}
>
Восстановить
</Button>
</>
}
/>
)
},
),
})
setlessonToDelete(null)
}
@ -134,20 +233,34 @@ const LessonList = () => {
useEffect(() => {
if (crLQuery.isSuccess) {
const values = getValues()
if (toastRef.current) {
toast.update(toastRef.current, {
const toastProps = {
title: 'Лекция создана',
description: `Лекция ${values.name} успешно создана`,
status: 'success',
description: `Лекция ${createdLessonRef.current.name} успешно создана`,
status: 'success' as 'success',
duration: 9000,
isClosable: true,
})
}
reset()
if (toastRef.current) toast.update(toastRef.current, toastProps)
else toast(toastProps)
setShowForm(false)
}
}, [crLQuery.isSuccess])
useEffect(() => {
if (updateLessonRqst.isSuccess) {
const toastProps = {
title: 'Лекция Обновлена',
description: `Лекция ${createdLessonRef.current.name} успешно обновлена`,
status: 'success' as 'success',
duration: 9000,
isClosable: true,
}
if (toastRef.current) toast.update(toastRef.current, toastProps)
else toast(toastProps)
setShowForm(false)
}
}, [updateLessonRqst.isSuccess])
if (isLoading) {
return (
<Container maxW="container.xl">
@ -220,85 +333,17 @@ const LessonList = () => {
{isTeacher(user) && (
<Box mt="15" mb="15">
{showForm ? (
<Card align="left">
<CardHeader display="flex">
<Heading as="h2" mt="0">
Создание лекции
</Heading>
<CloseButton ml="auto" onClick={() => setShowForm(false)} />
</CardHeader>
<CardBody>
<form onSubmit={handleSubmit(onSubmit)}>
<VStack spacing="10" align="left">
<Controller
control={control}
name="date"
rules={{ required: 'Обязательное поле' }}
render={({ field }) => (
<FormControl>
<FormLabel>Дата</FormLabel>
<Input
{...field}
required={false}
placeholder="Укажите дату лекции"
size="md"
type="datetime-local"
<LessonForm
key={editLesson?._id}
isLoading={crLQuery.isLoading}
onSubmit={onSubmit}
onCancel={() => {
setShowForm(false)
setEditLesson(null)
}}
error={(crLQuery.error as any)?.error}
lesson={editLesson}
/>
{errors.date ? (
<FormErrorMessage>
{errors.date?.message}
</FormErrorMessage>
) : (
<FormHelperText>
Укажите дату и время лекции
</FormHelperText>
)}
</FormControl>
)}
/>
<Controller
control={control}
name="name"
rules={{ required: 'Обязательное поле' }}
render={({ field }) => (
<FormControl
isRequired
isInvalid={Boolean(errors.name)}
>
<FormLabel>Название новой лекции:</FormLabel>
<Input
{...field}
required={false}
placeholder="Название лекции"
size="md"
/>
{errors.name && (
<FormErrorMessage>
{errors.name.message}
</FormErrorMessage>
)}
</FormControl>
)}
/>
<Box mt="10">
<Button
size="lg"
type="submit"
leftIcon={<AddIcon />}
colorScheme="blue"
>
Создать
</Button>
</Box>
</VStack>
{crLQuery.error && (
<ErrorSpan>{(crLQuery.error as any).error}</ErrorSpan>
)}
</form>
</CardBody>
</Card>
) : (
<Box p="2" m="2">
<Button
@ -356,7 +401,14 @@ const LessonList = () => {
<EditIcon />
</MenuButton>
<MenuList>
<MenuItem isDisabled>Edit</MenuItem>
<MenuItem
onClick={() => {
setShowForm(true)
setEditLesson(lesson)
}}
>
Edit
</MenuItem>
<MenuItem onClick={() => setlessonToDelete(lesson)}>
Delete
</MenuItem>

View File

@ -45,4 +45,12 @@ router.get('/lesson/:lessonId', (req, res) => {
res.send(require('../mocks/lessons/byid/success.json'))
})
router.delete('/lesson/:lessonId', (req, res) => {
res.send({ success: true, body: { ok: true }})
})
router.put('/lesson/:lessonId', (req, res) => {
res.send({ success: true, body: req.body })
})
module.exports = router