Skip to content

Instantly share code, notes, and snippets.

@argentinaluiz
Last active September 10, 2022 14:29
Show Gist options
  • Save argentinaluiz/7ab7aca820ecd941fd369f0fa5d902be to your computer and use it in GitHub Desktop.
Save argentinaluiz/7ab7aca820ecd941fd369f0fa5d902be to your computer and use it in GitHub Desktop.
Melhorias react
import { Course, StudentCourseStats } from "./model";
import axios, { AxiosInstance } from "axios";
import { IS_TEST, API_HOST, API_HOST_TEST } from "../constants";
export const api = axios.create({
baseURL: IS_TEST ? API_HOST_TEST : API_HOST,
});
export class HttpResource {
constructor(public http: AxiosInstance, public resource: string) {}
list<T = any>(): Promise<T> {
return this.http.get(this.resource).then((res) => res.data);
}
}
export class CategoryCourseHttp extends HttpResource {
categoryId: number;
constructor(public http: AxiosInstance, categoryId: number) {
super(http, `categories/${categoryId}/courses`);
this.categoryId = categoryId;
}
}
export class StudentStatsCourseHttp extends HttpResource {
categoryId: number;
studentId: number;
constructor(
public http: AxiosInstance,
studentId: number,
categoryId: number
) {
super(
http,
`/students/${studentId}/stats-course?category=${categoryId}`
);
this.categoryId = categoryId;
this.studentId = studentId;
}
async list(): Promise<StudentCourseStats[]> {
const courseHttp = new CategoryCourseHttp(this.http, this.categoryId);
const courses = await courseHttp.list<Course[]>();
type CourseStats = Omit<StudentCourseStats, "course">;
const courseStats = await super.list<CourseStats[]>();
const stats = courses.map((course) => {
const stats: StudentCourseStats = {
percentage: 0,
last_interaction: null,
contents_finished: 0,
course,
};
const courseStat = courseStats.find(
(stats) => course._id === stats._id
);
if (courseStat) {
stats.contents_finished = courseStat.contents_finished;
stats.last_interaction = courseStat.last_interaction as any;
stats.percentage =
(100 * courseStat.contents_finished!) /
courseStat.contents_total;
}
return stats;
});
return stats.sort((a: StudentCourseStats, b: StudentCourseStats) => {
return a.percentage > b.percentage
? -1
: a.percentage < b.percentage
? 1
: 0;
});
}
}
//lodash npm install lodash npm install @types/lodash --save-dev isEqual(array1, array2)
//swr - stale while revalidate
import React from 'react';
import { ChakraProvider } from '@chakra-ui/react'
import { ThemeProvider } from '@material-ui/core'
import { theme, themeMaterial } from './global/theme';
import { Routers } from './routers'
import { PersistGate } from 'redux-persist/integration/react';
import { Provider } from 'react-redux'
import { store, persistor } from './store'
const App: React.FC = () => {
return (
<Provider store={store}>
<PersistGate persistor={persistor}>
<ChakraProvider resetCSS theme={theme}>
<ThemeProvider theme={themeMaterial}>
<ErrorBoundary>
<Routers />
</ErrorBoundary>
</ThemeProvider>
</ChakraProvider>
</PersistGate>
</Provider>
)
}
export default App;
import { useCallback, useEffect, useState } from "react";
import { Flex, Text } from "@chakra-ui/react";
import Drawer from "../../components/Drawer";
import { HeaderBar } from "../../components/HeaderBar";
import { Card } from "../../components/Card";
import { CardCategorie } from "../../components/CardCategorie";
import { Grid } from "@material-ui/core";
import { useParams } from "react-router-dom";
import {
api,
CategoryCourseHttp,
CourseHttp,
StudentStatsCourseHttp,
} from "../../services/api";
import { Course } from "../../services/model";
interface RouterParamsProps {
id: string;
}
interface CategoriesProps {
_id: number;
name: string;
classroom_id: number;
classroom_name: string;
}
interface UserDataProps {
_id: number;
name: string;
email: string;
phone: string;
cellphone: string;
categories: CategoriesProps[];
last_interaction: string | null;
}
interface ModulesProps {
_id: number;
name: string;
contents_finished?: number;
last_interaction?: null | string;
contents_total: number;
percentage: number;
}
function Student() {
const [courseName, setCourseName] = useState("");
const params = useParams<RouterParamsProps>();
const [userData, setUserData] = useState<UserDataProps>({
_id: 0,
name: "",
email: "",
phone: "",
cellphone: "",
categories: [],
last_interaction: "",
});
const [modules, setModules] = useState<ModulesProps[]>([]);
const funcao = useCallback((param1, param2) => {
return param1 + param2;
}, []);
async function hasndleModules(id: number, name: string) {
setCourseName(name);
// const courses = await new CategoryCourseHttp(api, id).list<Course[]>();
// let { data: response }: { data: ModulesProps[] } = await api.get(
// `/categories/${id}/courses`
// );
// const { data: responseFinishedContent }: { data: ModulesProps[] } =
// await api.get(`/students/${params.id}/stats-course?category=${id}`);
// response = response.map((item) => {
// const [value] = responseFinishedContent.filter(
// (dadosItem) => item._id === dadosItem._id
// );
// if (value) {
// item.contents_finished = value.contents_finished;
// item.last_interaction = value.last_interaction;
// item.percentage =
// (100 * value.contents_finished!) / item.contents_total;
// return item;
// }
// item.percentage = 0;
// item.last_interaction = null;
// item.contents_finished = 0;
// return item;
// });
// response = response.sort((a: ModulesProps, b: ModulesProps) => {
// return a.percentage > b.percentage
// ? -1
// : a.percentage < b.percentage
// ? 1
// : 0;
// });
}
useEffect(() => {
async function Home() {
const { data: response } = await api.get(`/students/${params.id}`);
const [{data: courses}, {data: students}, response3] = Promise.all([axios1.get(), axios2.get()]);
setUserData(response);
}
Home();
}, []);
useEffect(() => {
(async () => {
try{
const stats = await new StudentStatsCourseHttp(
api,
params.id,
id
).list();
setModules(stats);
}catch(e){
setModules(() => throw e)
}
})();
}, [studentId, categoryId]);
//ErrorBoundary - formatar error e outro pra logs, mostrar
render (){
pagina error
}
return (
<Drawer>
<Flex direction="column">
<HeaderBar
name={userData.name}
email={userData.email}
lastAccess={userData.last_interaction}
/>
</Flex>
<Flex mt="50px" direction="column">
<Text fontSize="22px" fontWeight="semibold">
Cursos
</Text>
<Flex maxW="100%">
<Grid container>
{userData.categories.map((item, index) => (
<Card
key={index}
id={item._id}
name={item.name}
onClick={hasndleModules}
/>
))}
<Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
<Flex mt="20px" h="1px" w="100%" bg="border" />
</Grid>
</Grid>
</Flex>
</Flex>
<Flex
mt="50px"
direction="column"
bg="backgroundCard"
p="2"
borderRadius="2px"
>
<Flex mb="30px" mt="20px" align="center">
<Text fontSize="22px" fontWeight="semibold">
Módulos
</Text>
<Text ml="5" fontSize="18px">
{courseName}
</Text>
</Flex>
<Flex maxW="100%">
<Grid container>
{modules.map((item, index) => (
<CardCategorie
key={index}
lastInteraction={item.last_interaction!}
contentsFinished={item.contents_finished!}
percentage={item.percentage}
name={item.name}
contentsTotal={item.contents_total}
/>
))}
<Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
<Flex mt="20px" h="1px" w="100%" bg="border" />
</Grid>
</Grid>
</Flex>
</Flex>
</Drawer>
);
}
export { Student };
export interface Course {
_id: string;
name: string;
}
export interface StudentCourseStats {
_id: string;
contents_finished: number;
contents_total: number;
last_interaction: string | null;
percentage: number;
course: Course;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment