frontend/src/contexts/StudentsProvider.tsx

55 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-12-12 20:32:09 +01:00
import React, { useState, createContext, useEffect, ReactNode, useRef, useContext } from 'react';
2020-12-12 19:57:16 +01:00
import { Student } from '../types';
import { axiosInstance } from '../utils/axiosInstance';
interface StudentContext {
students: Array<Student>;
2020-12-16 00:23:31 +01:00
selectedStudent: Student | null;
changeSelectedStudent: (studentId: number) => void;
2020-12-12 19:57:16 +01:00
}
export const studentsContext = createContext<StudentContext | undefined>(undefined);
interface StudentsProviderProps {
children: ReactNode;
}
export const StudentsProvider = ({ children }: StudentsProviderProps) => {
const [students, setStudents] = useState<Array<Student>>([]);
2020-12-16 00:23:31 +01:00
const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
2020-12-12 19:57:16 +01:00
const getStudents = async () => {
try {
const { data } = await axiosInstance.get<Array<Student>>(
`${process.env.REACT_APP_API_URL}/api/v1/users/students`,
);
setStudents(data);
} catch (e) {
console.log(e);
}
};
2020-12-16 00:23:31 +01:00
const changeSelectedStudent = (studentId: number) => {
setSelectedStudent(students.find((student) => student.id === studentId)!);
};
2020-12-12 19:57:16 +01:00
useEffect(() => {
setTimeout(() => {
2020-12-29 01:06:39 +01:00
const userPrivilige = localStorage.getItem('userPrivilige');
userPrivilige === 'DEANERY' && getStudents();
2020-12-12 19:57:16 +01:00
}, 500);
}, []);
return (
<studentsContext.Provider
value={{
2020-12-16 00:23:31 +01:00
selectedStudent,
2020-12-12 19:57:16 +01:00
students,
2020-12-16 00:23:31 +01:00
changeSelectedStudent,
2020-12-12 19:57:16 +01:00
}}
>
{children}
</studentsContext.Provider>
);
};