'useFetch hook based on use cases causes infinite loop

I tried to create a useFetch hook based on diferent use-case and I can't deal with this task.

First of all, I have a service, a repository and then call a use-case:

const userService = new UserServiceImpl(apiConfig);
const uploadImageService = new AmplifyS3Service();
const userRepository = new UserRepositoryImpl(
   userService,
   uploadImageService
);
const getUserUseCase = new GetUserUseCaseImpl(userRepository);

I would like to optimize every tasks, fetch data from getUserUseCase because returns a Promise, put on the state and map trough data. My whole application is based on use-cases

const [user, setUser] = useState<User>();
getUserUseCase.getUser().then(setUser)

I tried to create a useFetch hook:

import { useEffect, useState } from "react";

export const useFetch = (useCase: Promise<any>) => {
  const [state, setState] = useState({
    data: null,
    loading: true,
    error: null,
  });

  useEffect(() => {
    useCase.then((data) => {
      setState({
        data,
        loading: false,
        error: null,
      });
    });
  }, [useCase]);

  return state;
};

and then I call it passing a use-case by argument...

const userInfo = getUserUseCase.getUser();
const { data, loading } = useFetch(userInfo);

after this point, I get a infinite loop, and I don't know which part I'm doing wrong.
Any help will be appreciate.
Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source