import { useEffect, useState, useCallback } from "react";
import { User } from "../interfaces/user";
import axios from "axios";

export default function useUserData({
  userId,
}: {
  userId: string;
}) {
  const [userData, setUserData] = useState<User | undefined>(undefined);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  const getData = useCallback(() => {
    if (!userId ) return;
    setIsLoading(true);
    axios
      .get(`/api/users/${userId}`)
      .then((response) => setUserData(response.data))
      .finally(() => setIsLoading(false))
      .catch((error) => setIsError(true));
  }, [userId]);

  useEffect(getData, [getData]);

  return { userData, isLoading, isError, reload: getData };
}
