All files / src/contexts StudentsProvider.tsx

52.94% Statements 9/17
0% Branches 0/2
33.33% Functions 2/6
56.25% Lines 9/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                    5x           5x 10x 10x   10x                     10x       10x 10x           10x                        
import React, { useState, createContext, useEffect, ReactNode, useRef, useContext } from 'react';
import { Student } from '../types';
import { axiosInstance } from '../utils/axiosInstance';
 
interface StudentContext {
  students: Array<Student>;
  selectedStudent: Student | null;
  changeSelectedStudent: (studentId: number) => void;
}
 
export const studentsContext = createContext<StudentContext | undefined>(undefined);
 
interface StudentsProviderProps {
  children: ReactNode;
}
 
export const StudentsProvider = ({ children }: StudentsProviderProps) => {
  const [students, setStudents] = useState<Array<Student>>([]);
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
 
  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);
    }
  };
 
  const changeSelectedStudent = (studentId: number) => {
    setSelectedStudent(students.find((student) => student.id === studentId)!);
  };
 
  useEffect(() => {
    setTimeout(() => {
      const userPrivilige = localStorage.getItem('userPrivilige');
      userPrivilige === 'DEANERY' && getStudents();
    }, 500);
  }, []);
 
  return (
    <studentsContext.Provider
      value={{
        selectedStudent,
        students,
        changeSelectedStudent,
      }}
    >
      {children}
    </studentsContext.Provider>
  );
};