feat: creating lesson with hook

This commit is contained in:
Sergey Yarkov 2022-01-05 18:59:41 +03:00
parent 10d2cf3782
commit ce46c7a739
8 changed files with 109 additions and 45 deletions

12
package-lock.json generated
View File

@ -1072,9 +1072,9 @@
}
},
"@hookform/resolvers": {
"version": "2.8.2",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-2.8.2.tgz",
"integrity": "sha512-oDTGrm7yHxT4VIv4kJcfjvWvozCbdcL0/jrpbAkeo39FYn78XnKOrrGTNmrXdfu+EQVkNIdZ47IYRFManZ4jUA=="
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-2.8.5.tgz",
"integrity": "sha512-n7eFm4snsejpfZVH8q2NU7YJbsGhF61IHB0TxgK11nmg08RymEr3KscnbTAZaPd9RaXa3vUPoULgBRN2nVDtMg=="
},
"@humanwhocodes/config-array": {
"version": "0.9.2",
@ -3320,9 +3320,9 @@
}
},
"react-hook-form": {
"version": "7.17.4",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.17.4.tgz",
"integrity": "sha512-7XhbCr7d9fDC1TgcK/BUbt7D3q0VJMu7jPErfsa0JrxVjv/nni41xWdJcy0Zb7R+Np8OsCkQ2lMyloAtE3DLiQ=="
"version": "7.22.5",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.22.5.tgz",
"integrity": "sha512-Q2zaeQFXdVQ8l3hcywhltH+Nzj4vo50wMVujHDVN/1Xy9IOaSZJwYBXA2CYTpK6rq41fnXviw3jTLb04c7Gu9Q=="
},
"react-icons": {
"version": "4.3.1",

View File

@ -13,7 +13,7 @@
"@chakra-ui/react": "^1.6.10",
"@emotion/react": "^11.5.0",
"@emotion/styled": "^11.3.0",
"@hookform/resolvers": "^2.8.0",
"@hookform/resolvers": "^2.8.5",
"axios": "^0.21.1",
"framer-motion": "^4.0.0",
"js-cookie": "^3.0.0",
@ -26,7 +26,7 @@
"react-dom": "^17.0.0",
"react-error-boundary": "^3.1.3",
"react-helmet": "^6.1.0",
"react-hook-form": "^7.12.2",
"react-hook-form": "^7.22.5",
"react-icons": "^4.3.1",
"react-player": "^2.9.0",
"react-router-dom": "^5.2.0",

View File

@ -2,20 +2,33 @@ import { yupResolver } from '@hookform/resolvers/yup';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { LessonForm } from '.';
import { InputFields } from './LessonForm';
import type { InputFields } from './LessonForm';
import LessonFormSchema from './LessonForm.validator';
import { useCreateLesson } from '@educt/hooks/queries';
import { useHistory, useParams } from 'react-router-dom';
const CreateLessonForm: React.FC = () => {
const form = useForm<InputFields>({ resolver: yupResolver(LessonFormSchema) });
const { createLesson, isLoading } = useCreateLesson();
const { id: course_id } = useParams<{ id: string }>();
const history = useHistory();
const onSubmit: SubmitHandler<InputFields> = async data => {
console.log('creating...');
console.log(data);
const lesson = await createLesson({
title: data.title,
description: data.description,
duration: data.duration,
video: data.video,
materials: Array.from(data.materials || []),
course_id,
});
console.log(`created: ${lesson}`);
history.push(`/courses/edit/${course_id}`);
};
return (
<LessonForm
isLoading={false}
isLoading={isLoading}
reactHookForm={{ ...form }}
onSubmit={form.handleSubmit(onSubmit)}
buttonLabel='Create'

View File

@ -23,7 +23,7 @@ export type InputFields = {
description: string;
duration: string;
video: File;
materials?: File[] | undefined;
materials?: FileList | undefined;
};
export type LessonFormPropsType = {
@ -99,7 +99,7 @@ const LessonForm: React.FC<LessonFormPropsType> = ({ onSubmit, buttonLabel, isLo
control={control}
name='materials'
render={({ field: { onChange, value: files } }) => (
<FilesUploader onChange={files => onChange(files)} files={files} />
<FilesUploader onChange={files => onChange(files)} files={Array.from(files || [])} />
)}
/>
<Text as='small' color='red.500'>

View File

@ -4,7 +4,8 @@ import yup from '@educt/schema';
const VIDEO_FILE_SIZE = 5000 * 1024 * 1024;
const MATERIAL_FILE_SIZE = 100000 * 1024;
const LessonFormSchema = yup.object().shape({
const LessonFormSchema = yup
.object({
title: yup.string().required('Title field name is required').max(90, 'Title must be at most 90 characters'),
description: yup
.string()
@ -33,6 +34,7 @@ const LessonFormSchema = yup.object().shape({
}
)
.optional(),
});
})
.required();
export default LessonFormSchema;

View File

@ -7,6 +7,7 @@ import { useLogout } from './auth/useLogout';
/**
* Lesson
*/
import { useCreateLesson } from './lesson/useCreateLesson';
import { useDeleteLesson } from './lesson/useDeleteLesson';
/**
@ -36,6 +37,7 @@ export {
useSetCourseStatus,
useAttachStudents,
useDetachStudents,
useCreateLesson,
useDeleteLesson,
useCreateUser,
useDeleteUser,

View File

@ -0,0 +1,45 @@
import axios from 'axios';
import { ILesson } from '@educt/interfaces';
import { LessonServiceInstance } from '@educt/services';
import type { CreateLessonParamsType } from '@educt/types';
import useAsync from '@educt/hooks/useAsync';
import { useErrorHandler } from 'react-error-boundary';
import { useToast } from '@chakra-ui/react';
const useCreateLesson = () => {
const toast = useToast();
const handleError = useErrorHandler();
const createLesson = async (data: CreateLessonParamsType) => {
try {
const result = await LessonServiceInstance.create(data);
toast({ title: `Lesson successfully created.`, status: 'success' });
return result.data;
} catch (error: unknown) {
if (axios.isAxiosError(error)) {
if (error.response) {
switch (error.response.status) {
case 422:
toast({ title: `${error.response.data.errors[0].message}`, status: 'error' });
break;
default:
toast({ title: `${error.message}`, status: 'error' });
break;
}
} else {
handleError(error);
}
} else {
handleError(error);
}
return Promise.reject(error);
}
};
const { execute, ...state } = useAsync<ILesson, Parameters<typeof createLesson>>(createLesson);
return { createLesson: execute, ...state };
};
export { useCreateLesson };

View File

@ -1,4 +1,5 @@
import { AxiosInstance } from 'axios';
import * as helpers from '@educt/helpers';
import { IApiRespose, ILesson } from '@educt/interfaces';
import { ApiServiceInstance } from './ApiService';
import type { CreateLessonParamsType, LessonProgress } from '@educt/types';
@ -49,7 +50,8 @@ class LessonService {
* @param data Lesson data for creating
*/
public async create(data: CreateLessonParamsType): Promise<IApiRespose<ILesson>> {
console.log(data);
const result = await this.api.post(`/v1/lessons`, helpers.transformToFormData(data));
return result.data;
}
/**