[React - Moralis] Unhandled Rejection Error

I am trying to get the Price of a coin on Uniswap (in this case the Uniswap token) via a cloud function call.

I get this error. When I press the “Get Price” button within App.js. It calls the GetPrice function

Here is the cloud function

Moralis.Cloud.define("getPrice", async (request) => {
  let url = 'https://deep-index.moralis.io/api/token/ERC20/' + request.params.address + '/price'
  logger.info(url);
  return Moralis.Cloud.httpRequest({
  url: url,
  params: {chain: "eth", chain_name: "mainnet"},
  headers: {
    'accept': 'application/json',
    'X-API-Key': 'API-KEY-GOES-HERE' 
    }
  }).then( function(httpResponse){
    return httpResponse.data;
  }, function(httpResponse){
    	logger.info("error");
    	logger.info(httpResponse);
  })
});

Here is App.js

import {useMoralis, useMoralisCloudFunction} from "react-moralis";
import {
    Alert,
    AlertDescription,
    AlertIcon,
    AlertTitle,
    Box,
    Button,
    CloseButton,
    Container,
    Heading
} from "@chakra-ui/react";

async function GetPrice() {
    let address = "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"; //uniswap
    let price = await useMoralisCloudFunction("getPrice", {address: address});
    let ethPrice = (price.nativePrice.value / (10**price.nativePrice.decimals)) + " ETH";
    let usdPrice = price.usdPrice + " USD";
    console.log(ethPrice + usdPrice);

}

function App() {
    const {authenticate, isAuthenticated, isAuthenticating, authError, logout} = useMoralis();

    if(isAuthenticated){
        return (
            <Container>
               <Heading>Welcome to the website</Heading>
                <Button onClick={() => logout()}>Logout</Button>
                <Button onClick={() => GetPrice()}>Get Price</Button>

            </Container>
        )
    }

  return (
    <div>
      HexAbout
        {authError && (
            <Alert status="failed">
                <AlertIcon />
                <Box flex="1">
                    <AlertTitle>Authentication Failed</AlertTitle>
                    <AlertDescription display="block">
                        {authError.message}
                    </AlertDescription>
                </Box>
                <CloseButton position="absolute" right="8px" top="8px" />
            </Alert>
        )}
        <Button onClick={() => authenticate()} isLoading={isAuthenticating}>Authenticate</Button>
    </div>
  );
}

export default App;

Here is the index

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {ChakraProvider, extendTheme} from "@chakra-ui/react";
import { MoralisProvider } from "react-moralis";

const appId = "";
const serverUrl = "";

const theme = extendTheme({
    config: {
        initialColorMode: "dark",
    },
});


ReactDOM.render(
  <MoralisProvider appId={appId} serverUrl={serverUrl}>
      <ChakraProvider theme={theme}>
          <App />
      </ChakraProvider>
  </MoralisProvider>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Hey @IntrepidShape

The error message tells you about the problem. Make changes in App.js. You need to “teleport” function GetPrice() to the component App body:

import {useMoralis, useMoralisCloudFunction} from "react-moralis";
import {
   Alert,
   AlertDescription,
   AlertIcon,
   AlertTitle,
   Box,
   Button,
   CloseButton,
   Container,
   Heading
} from "@chakra-ui/react";

function App() {
   const {authenticate, isAuthenticated, isAuthenticating, authError, logout} = useMoralis();
async function GetPrice() {
   let address = "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"; //uniswap
   let price = await useMoralisCloudFunction("getPrice", {address: address});
   let ethPrice = (price.nativePrice.value / (10**price.nativePrice.decimals)) + " ETH";
   let usdPrice = price.usdPrice + " USD";
   console.log(ethPrice + usdPrice);

}

   if(isAuthenticated){
       return (
           <Container>
              <Heading>Welcome to the website</Heading>
               <Button onClick={() => logout()}>Logout</Button>
               <Button onClick={() => GetPrice()}>Get Price</Button>

           </Container>
       )
   }

 return (
   <div>
     HexAbout
       {authError && (
           <Alert status="failed">
               <AlertIcon />
               <Box flex="1">
                   <AlertTitle>Authentication Failed</AlertTitle>
                   <AlertDescription display="block">
                       {authError.message}
                   </AlertDescription>
               </Box>
               <CloseButton position="absolute" right="8px" top="8px" />
           </Alert>
       )}
       <Button onClick={() => authenticate()} isLoading={isAuthenticating}>Authenticate</Button>
   </div>
 );
}

export default App;

Let me know how it will work for you

1 Like

I took the function GetPrice() and placed it within the App() function (I’m new to React so putting a function definition within another function seemed weird to me)

I still get the exact same error.

New Code

import {useMoralis, useMoralisCloudFunction} from "react-moralis";
import {
    Alert,
    AlertDescription,
    AlertIcon,
    AlertTitle,
    Box,
    Button,
    CloseButton,
    Container,
    Heading
} from "@chakra-ui/react";

function App() {
    const {authenticate, isAuthenticated, isAuthenticating, authError, logout} = useMoralis();
    async function GetPrice() {
        let address = "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"; //uniswap
        let price = await useMoralisCloudFunction("getPrice", {address: address});
        let ethPrice = (price.nativePrice.value / (10**price.nativePrice.decimals)) + " ETH";
        let usdPrice = price.usdPrice + " USD";
        console.log(ethPrice + usdPrice);

    }

    if(isAuthenticated){
        return (
            <Container>
                <Heading>Welcome to the website</Heading>
                <Button onClick={() => logout()}>Logout</Button>
                <Button onClick={() => GetPrice()}>Get Price</Button>

            </Container>
        )
    }

    return (
        <div>
            HexAbout
            {authError && (
                <Alert status="failed">
                    <AlertIcon />
                    <Box flex="1">
                        <AlertTitle>Authentication Failed</AlertTitle>
                        <AlertDescription display="block">
                            {authError.message}
                        </AlertDescription>
                    </Box>
                    <CloseButton position="absolute" right="8px" top="8px" />
                </Alert>
            )}
            <Button onClick={() => authenticate()} isLoading={isAuthenticating}>Authenticate</Button>
        </div>
    );
}

export default App;

this is the error I get after recompiling and “npm start” Then pressing the get price button.

How do I check if there is a mismatch of React Versions? Is React Moralis not being nice with standard React?

Oh, sorry. My bad, I haven’t noticed:

let price = await useMoralisCloudFunction("getPrice", {address: address});

You can’t call hook this way. Change the App component:

import {useMoralis, useMoralisCloudFunction} from "react-moralis";
import {
    Alert,
    AlertDescription,
    AlertIcon,
    AlertTitle,
    Box,
    Button,
    CloseButton,
    Container,
    Heading
} from "@chakra-ui/react";

function App() {
    const {authenticate, isAuthenticated, isAuthenticating, authError, logout} = useMoralis();
    const { data : price } = useMoralisCloudFunction("getPrice", {address: address});

    async function GetPrice() {
      if (price) {
        let address = "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"; //uniswap
        let ethPrice = (price.nativePrice.value / (10**price.nativePrice.decimals)) + " ETH";
        let usdPrice = price.usdPrice + " USD";
        console.log(ethPrice + usdPrice);
     }

    }

    if(isAuthenticated){
        return (
            <Container>
                <Heading>Welcome to the website</Heading>
                <Button onClick={() => logout()}>Logout</Button>
                <Button onClick={() => GetPrice()}>Get Price</Button>

            </Container>
        )
    }

    return (
        <div>
            HexAbout
            {authError && (
                <Alert status="failed">
                    <AlertIcon />
                    <Box flex="1">
                        <AlertTitle>Authentication Failed</AlertTitle>
                        <AlertDescription display="block">
                            {authError.message}
                        </AlertDescription>
                    </Box>
                    <CloseButton position="absolute" right="8px" top="8px" />
                </Alert>
            )}
            <Button onClick={() => authenticate()} isLoading={isAuthenticating}>Authenticate</Button>
        </div>
    );
}

export default App;

Yes! I we must have just realised this at the same time. I was calling it wrong. I managed to get it to debug the hookcall. Thanks! You code works too. Very much appreciated.

1 Like

Great job @IntrepidShape :muscle: :man_factory_worker:

Happy BUIDLing :man_mechanic: