API calls run twice on page load
Answered
Turkish Angora posted this in #help-forum
Turkish AngoraOP
I'm creating a blockchain explorer as a project for my resume. To do this, I'm loading a bunch of APIs.
Whenever I load my page, no matter how I change the UseEffect() function, my API gets fetched twice:
I'm slightly new to NextJs, so Id really appreciate if I can get help in ensuring the fetch only happens once.
Whenever I load my page, no matter how I change the UseEffect() function, my API gets fetched twice:
const WalletContent: React.FC<WalletID> = ({ walletName }) => {
const [holdings, setHoldings] = useState<any[]>([]);
useEffect(() => {
const getTransfers = async () => {
try {
await Moralis.start({
apiKey: "lol"
});
const response = await Moralis.EvmApi.token.getWalletTokenBalances({
"chain": "0x1",
"address": walletName
});
setHoldings(response.result);
} catch (e) {
console.error(e);
}
};
getTransfers();
}, []);I'm slightly new to NextJs, so Id really appreciate if I can get help in ensuring the fetch only happens once.
Answered by @ts-ignore
this is not specific to nextjs but react, useEffect runs twice in strict mode
11 Replies
Answer
Turkish AngoraOP
I read the documentation and its recommended to keep strict mode on
Is there a better way to fetch APIs to avoid this?
you can either copy the
useEffectOnce hook or follow the patternTurkish AngoraOP
thank you so much bro
Ill take a read now
@Turkish Angora I'm creating a blockchain explorer as a project for my resume. To do this, I'm loading a bunch of APIs.
Whenever I load my page, no matter how I change the UseEffect() function, my API gets fetched twice:
`const WalletContent: React.FC<WalletID> = ({ walletName }) => {
const [holdings, setHoldings] = useState<any[]>([]);
useEffect(() => {
const getTransfers = async () => {
try {
await Moralis.start({
apiKey: "lol"
});
const response = await Moralis.EvmApi.token.getWalletTokenBalances({
"chain": "0x1",
"address": walletName
});
setHoldings(response.result);
} catch (e) {
console.error(e);
}
};
getTransfers();
}, []);`
I'm slightly new to NextJs, so Id really appreciate if I can get help in ensuring the fetch only happens once.
Plott Hound
is the api key supposed to be secure? because currently its exposed to the client
Turkish AngoraOP
I know, I plan to put it in its own .env file when Im close to deploying
Oriental chestnut gall wasp
I know this was answered, but you should not need to be making api calls in a useEffect in nextjs. Are you using the app directory?
@Oriental chestnut gall wasp I know this was answered, but you should not need to be making api calls in a useEffect in nextjs. Are you using the app directory?
@Turkish Angora this is true and would address your issue. Hydrate rq with a server query.