Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!