frontend/src/contexts/StudentsProvider.tsx

61 lines
1.6 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';
2020-12-12 20:32:09 +01:00
import { CASContext } from './CASProvider';
2020-12-12 19:57:16 +01:00
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
2020-12-12 20:32:09 +01:00
//not working currently
2020-12-12 19:57:16 +01:00
const userPrivilige = localStorage.getItem('userPrivilige');
2020-12-12 20:32:09 +01:00
const { user } = useContext(CASContext)!;
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);
console.log(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-12 20:32:09 +01:00
// user?.authorityRole === '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>
);
};