import { useEffect } from "react";
import { useDispatch } from "react-redux";

import { useAccounts } from "@hooks/useAccounts";
import {
	setShortTokenList,
	setSupportedChains,
} from "../../../store/globalSlice";
import { useChains } from "./useChains";
import { useFetchTokens } from "./useTokens";

export const useFetchData = () => {
	const dispatch = useDispatch();
	const { accounts } = useAccounts();

	const supportedChains = useChains();
	const { data: shortTokenList } = useFetchTokens({
		addresses: accounts
			.map((account) => account.address)
			.filter((address) => address !== undefined),
	});

	useEffect(() => {
		if (supportedChains?.length) {
			dispatch(setSupportedChains(supportedChains));
		}
	}, [supportedChains, dispatch]);

	useEffect(() => {
		if (shortTokenList) {
			dispatch(setShortTokenList(shortTokenList));
		}
	}, [shortTokenList, dispatch]);

	return { supportedChains, shortTokenList };
};
