Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
how to use async function with custom hooks inside useEffects

i want the get the moralis useTokenPrice to fetch an updated price after every five seconds, but from the rules of hook a react hook cannot be used inside useEffects. how do i go about it.

my code

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;
}

what i have done

  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);
  }, []);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use hooks only in top level. But in your case useTokenPrice return fetch function which you can use everywhere:

  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;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda