React TypeScript Hook Passing Unexpected Props Object Instead of Null

clock icon

asked 8 months agoAsked

message

0Answers

eye

10Views

Problem Statement I'm experiencing an unexpected behavior with a custom React hook in TypeScript. When I pass null to the hook, it somehow receives an object containing the props of the component instead.

Code Here's parts of the code:

 

const useModuleData = (moduleId: number | null = null) => {
  const [data, setData] = useState<ModuleData>(initialData);
  const [isLoading, setIsLoading] = useState(true);
  const handleHttpError = useHttpErrorNavigate();

  console.log(moduleId); // error here: somehow gets props of the component which called it

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [teachersResponse, subjectsResponse] = await Promise.all([
          fetchAllTeachers(),
          fetchAllSubjects(),
        ]);

        if (!teachersResponse.success && teachersResponse.status !== 404) {
          handleHttpError(teachersResponse.status);
          return;
        }
        if (!subjectsResponse.success && subjectsResponse.status !== 404) {
          handleHttpError(subjectsResponse.status);
          return;
        }

        const moduleData = moduleId
          ? await fetchModuleSpecificData(moduleId, handleHttpError)
          : null;

        setData({
          teachers: teachersResponse.success ? teachersResponse.data : [],
          subjects: subjectsResponse.success ? subjectsResponse.data : [],
          ...moduleData,
        } as ModuleData);
      } catch (error) {
        console.error("Error fetching data:", error);
        handleHttpError(-1);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, [moduleId, handleHttpError]);

  return { ...data, isLoading };
};

0 Answers

Write your answer here

Top Questions