Vanilla => React (Cloudfunction call)

I’m trying to use React Moralis to call a cloud function.
I can retrieve the cloud function data using vanilla JS, but not using the react-moralis hooks.

I am trying to get the data to appear in the console but I can’t even get that with react atm.
I’m obviously missing something basic, but can’t figure out what.

CLOUD FUNCTION CODE (Working)

Moralis.Cloud.define("myCloudFunction", async (request) => {
  const query = new Moralis.Query("myClass");
  query.equalTo("address", request.params.user);
  const results = await query.find({useMasterKey:true});
  return results
});

VANILLA JS CODE (Working)

const params = {user: Moralis.User.current().get('ethAddress')}
const results = await Moralis.Cloud.run("myCloudFunction", params);
console.log(results)
// Result: (29) All good

REACT CODE (Not working)

import { useMoralisCloudFunction, useMoralis } from "react-moralis";
import { useEffect, useState, useMemo } from 'react';

function MyFunction() {

    const { user } = useMoralis()
    const userAddress = useMemo(() => user?.attributes.ethAddress, [user]);
    const { data: testData, isLoading } = useMoralisCloudFunction("myCloudFunction");
    const [thedata, setTheData] = useState("")

    useEffect(() => {
        if (!isLoading) {
          setTheData(testData);
          console.log("fetched")
          console.log(thedata)
          console.log(testData)
        }
      }, [testData])

  return (
      <></>
  );
}

export default MyFunction;

// REPONSE:
// fetched
// null
// null

Thanks for your help

const { fetch, data, error, isLoading } = useMoralisCloudFunction(
  "topScores",
  {
    limit
  },
  { autoFetch: false }
);

<button onClick={() => fetch()}>Fetch manually<button>

Thanks for pasting that snippet from the react-moralis github page. I’ve experimented with it before, the issue I’m having is not being able to see the data it returns on the front end.

If you could now just help me figure out why I can not render anything on the front end as I still receive ‘null’.

UPDATED REACT CODE (not working)

import { useMoralisCloudFunction, useMoralis } from "react-moralis";
import { useEffect, useState, useMemo } from 'react';

function MyFunction() {

    const { user } = useMoralis()
    const userAddress = useMemo(() => user?.attributes.ethAddress, [user]);
    const { fetch, data, isLoading } = useMoralisCloudFunction("myCloudFunction", userAddress, { autoFetch:false });
    const [thedata, setTheData] = useState("")

    useEffect(() => {
        if (!isLoading) {
            fetch()
            setTheData(data);
            console.log("fetched");
            console.log(data);
            console.log(thedata);
        }
      }, [data])

  return (
      <></>
  );
}

export default MyFunction;

Output from the console.log lines:

// "Fetched"
// Null
// ""

But the server dashboard tells me “Ran cloud function myCloudFunction for user xxxxxxxxx” and it shows results in the logs. So I’m missing something obvious about displaying the results. I appreciate this is probably a basic question, but I’m sure you know the answer.

Thanks

if you use awat fetch() changes anything?

you can also use Moralis.Cloud.run if you want in react

Sorry, but I can not use Moralis.Cloud.run in react. I get this error:

import { useMoralisDapp } from "../../../../src/providers/MoralisDappProvider/MoralisDappProvider";
import { useMoralisCloudFunction, useMoralis } from "react-moralis";

function MyFunction() {

    const { walletAddress } = useMoralisDapp();
    const Moralis = useMoralis()

    async function test(){
        const result = await Moralis.Cloud.run("myCloudFunction", { user: walletAddress });
        console.log(results)
    }
    test();

  return (
      <></>
  );
}

export default MyFunction;

I am really struggling to get past this simple step

I think I needed to run the function after the isAuthenticated check… something like:

const { Moralis, isAuthenticated } = useMoralis()

if(isAuthenticated){test();}

Because now I get results back… but I clearly have some basic react misunderstandings

this is an alternative syntax:

import React, { useState } from "react";
const Moralis = require("moralis");

function App2() {
  const [results, setResults] = useState("");
  Moralis.start({
    appId: "asdf",
    serverUrl: "https://asdfasdf:2053/server"
  });

  React.useEffect(() => {
    const asyncFunc = async () => {
      const x3 = await Moralis.Cloud.run("myCloudFunction");
      setResults(JSON.stringify(x3));
    };
    asyncFunc();
  }, []);

  return (
    <div>
      <p>test {results}</p>
    </div>
  );
}

export default App2;

2 Likes