React-Moralis getNFTBalances Returns Null Sometimes (Mostly First Call)?

I am trying to load in a user’s (hardcoded address rn) NFTs when my page loads in. Despite doing “await” for the getNFTBalances, the console.log for fetchedNFTs under it prints out “null.” I’ve tried using a button that calls getNFTs() and it seems that on first button press, it always prints “null,” but on second button press, it works (290 total). Anyone know what is up?

Also, I checked error, isLoading, and isFetching and error=null, isLoading=false, isFetching=false.

File I’m trying to load NFTs into


Index.js

At first, the data state is empty. This is due to the time you’re logging it and the way states are handles.
If you have onSuccess in your function such as below, you can get the response from the getNFTs. This is due to the way states are handles.

await getNFTBalances({
      params: {
        chain: "",
        address: ""
      },
      onSuccess: (result) => console.log(result) // This logs immediately
    });

Nonetheless, if you’re rendering something with the result, you can check if you got something before rendering.

The case is quite similar to having such

  const [data, setData] = useState("");
  function setNewData() {
    setData("New Data");
    console.log(data)     // This will log "" 
  }
1 Like

Oh wow, this makes a lot of sense. My code works now. Thanks!