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);
}, []);
useTokenPrice()?const {fetchTokenPrice, data} = useTokenPrice( ...)then usefetchTokenPrice()wherever you want.