Web3 React cloud Functions

Hello.


export const useChainsSynced = () => {
  const { user } = useMoralis();
  const userAddress = useMemo(() => user?.attributes.ethAddress, [user]);
  const { data: chains, isLoading } = useMoralisCloudFunction("getChains", {
    userAddress,
  });
  const [chainList, setChainList] = useState();
  useEffect(() => {
    if ([chains]?.length) {
      setChainList(chains);
      console.log("Data fetched");
    }
  }, [chains]);

  return { chainList, isLoading };
};

I use this hook only once in my code, but in console log i see “Data fetched” multiple times. Why? The logic is useEffect should be called twice(when starts fetching and when data: chains was fetched), isnt it? Or how to correctly wait until the data from Cloud functions wasnt fetched?

My bad, i fixed it.

export const useChainsSynced = () => {
  const { user } = useMoralis();
  const userAddress = useMemo(() => user?.attributes.ethAddress, [user]);
  const { data: chains, isLoading } = useMoralisCloudFunction("getChains", {
    userAddress,
  });
  const [chainList, setChainList] = useState();

  useEffect(() => {
    if (Object.keys(chains).length !== 0) {
      setChainList(chains);
      console.log("Data fetched");
      console.log(chains);
    };
  }, [chains]);

  return { chainList, isLoading };
};
1 Like