Quiero obtener el moralis useTokenPrice para obtener un precio actualizado cada cinco segundos, pero según las reglas del gancho, no se puede usar un gancho de reacción dentro de useEffects. ¿Cómo lo hago?
mi código
function SpeedPrice(props) { const [price, setPrice] = useState({ symbol: "", token_address: "", price: "", }); const MINUTE_MS = 5000; const address = props.address; const symbol = props.symbol; async function GetPrice() { const result = await useTokenPrice({ // moralis hook chain: "eth", address: address, }); const usdPrice = result.data.formattedUsd; setPrice({ symbol: symbol, token_address: address, price: usdPrice }); } // GetPrice(); infinite loop useEffect(() => { const interval = setInterval(() => { console.log("call getprice"); // GetPrice() error! React Hooks must be called in a React function component or a custom React Hook function }, MINUTE_MS); return () => clearInterval(interval); }, []); return price.price; }
que he hecho
useEffect(() => { const interval = setInterval(() => { // moved the function inside useEffects async function GetPrice() { const result = await useTokenPrice({ // moralis hook chain: "eth", address: address, }); const usdPrice = result.data.formattedUsd; setPrice({ symbol: symbol, token_address: address, price: usdPrice }); } GetPrice(); }, MINUTE_MS); return () => clearInterval(interval); }, []);
Puede usar ganchos solo en el nivel superior . Pero en su caso, use la función de fetch
de devolución useTokenPrice
que puede usar en todas partes:
const {fetchTokenPrice/*👈*/, data /*👈*/} = useTokenPrice({ chain: 'eth', address: address }); useEffect(() => { const interval = setInterval(async () => { console.log('call getprice'); await fetchTokenPrice(address); // 👈 }, MINUTE_MS); return () => clearInterval(interval); }, []); const usdPrice = data.formattedUsd; // 👈 return data.isLoading || data.isFetching ? 'Loading...' : usdPrice;