In a React function component (with TypeScript) I need to call two different custom hooks depending on a prop's value, considering that each hook is called through its own service by requesting an API which is forbidden for the other hook.
As React rules prohibit calling a hook conditionally, I try to figure out how to get a hook result depending on who is calling it.
So I first tried to call the hook conditionally (which is against the React rules):
import React from "react";
import { useMyTeachers } from "/services/student-service";
import { useMyStudents } from "/services/teacher-service";
interface MyComponentProps {
role: string;
}
export const MyComponent: React.FC<MyComponentProps> = ({ role }) => {
let myList;
if (role == "student") {
myList = useMyTeachers();
}
if (role == "teacher") {
myList = useMyStudents();
}
...
}
Then I tried to call both hooks unconditionally:
export const MyComponent: React.FC<MyComponentProps> = ({ role }) => {
const myTeachersList = useMyTeachers(); //requesting a for-student-use-only API
const myStudentsList = useMyStudents(); //requesting a for-teacher-use-only API
...
}
But in this case, a forbidden error is thrown in console because of the API restriction.