Get Function Integration

Follow the steps to integrate the view / read/ get function.

frontend/
    ├───components
    │   └───ui
    ├───entry-functions
    ├───lib
    ├───utils
    ├───view-functions
    ├───App.tsx
    ├───index.tsx

Navigate to the utils Directory and create a new TypeScript file in this directory. You might name it something like getFunction.ts

// src/utils/getFunction.ts

import { aptosClient } from "./aptosClient";

export const getFunction = async (accountAddress: string) => {
  try {
    const resourceType = "0xYourContractAddress::your_module::your_function_name";

    // Updated to pass an object with the expected properties
    const response = await aptosClient().getAccountResource({
      accountAddress,
      resourceType
    });
    console.log(response);
    
    return response && response.entries ? true : false;
  } catch (error) {
    console.error("Error checking if list exists:", error);
    return false;
  }
};

Here Replace,

0xYourContractAddress with your contract address (module address)

your_module with your module name (contract name)

your_function_name with your function name you need to call.

Now in App.tsx call the function like this:

const checkGetFunction = async () => {
    
    const resultval = await getFunction(account.address);
    setResult(resultval);
    console.log("Result:", result);
    
  };

The example App.tsx code is:

import { useWallet } from "@aptos-labs/wallet-adapter-react";
// Internal Components
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Header } from "@/components/Header";
import { WalletDetails } from "@/components/WalletDetails";
import { NetworkInfo } from "@/components/NetworkInfo";
import { AccountInfo } from "@/components/AcoountInfo";
// These are imported for integration
import { createEntry as createEntryFunction } from "@/entry-functions/integrateContract";
import React, { FormEvent, useState } from "react";
import { aptosClient } from "./utils/aptosClient";
import { useQueryClient } from "@tanstack/react-query";
//get function
import { getFunction } from "./utils/getFunction";

const App: React.FC = () => {
  const { connected, account, signAndSubmitTransaction } = useWallet();

  const [name, setName] = useState("");
  const [timestamp, setTimestamp] = useState("");
  const [result, setResult] = useState("");

  const queryClient = useQueryClient();
  
  const getFunctionResult = async () => {
    if (!account) {
      setResult("Account not connected");
      return;
    }

    try {
      const value = await getFunction(account.address);
      setResult(value);
    } catch (error) {
      console.error("Error fetching list:", error);
      setResult("Error fetching list");
    }
  };
  
  const handleCreateEntry = async (e: FormEvent) => {
    e.preventDefault();
    if (!account) return;

    try {
      const transactionData = createEntryFunction({
        name,
        timestamp,
      });
      
      const response = await signAndSubmitTransaction(transactionData);
      await aptosClient().waitForTransaction(response.hash);
      queryClient.invalidateQueries();
      setName("");
      setTimestamp("");
      alert("Entry created successfully");
    } catch (error) {
      console.error("Error creating entry:", error);
    }
  };

  return (
    <>
      <Header />

      <div className="flex items-center justify-center min-h-screen bg-gray-100">
        {connected ? (
          <div className="w-full max-w-lg p-6 bg-white shadow-lg rounded-lg">
            <Card>
              <CardContent className="flex flex-col gap-10 pt-6">
                <WalletDetails />
                <NetworkInfo />
                <AccountInfo />
              </CardContent>
            </Card>

            <div className="mt-6">
              <form onSubmit={handleCreateEntry} className="space-y-4">
                <div className="flex flex-col">
                  <label className="text-gray-700 font-medium">Name:</label>
                  <input
                    type="text"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    required
                    className="mt-1 p-2 border border-gray-300 rounded-lg"
                  />
                </div>
                <div className="flex flex-col">
                  <label className="text-gray-700 font-medium">Timestamp:</label>
                  <input
                    type="datetime-local"
                    value={timestamp}
                    onChange={(e) => setTimestamp(e.target.value)}
                    required
                    className="mt-1 p-2 border border-gray-300 rounded-lg"
                  />
                </div>
                <button
                  type="submit"
                  className="w-full bg-blue-500 text-white p-2 rounded-lg hover:bg-blue-600 transition"
                >
                  Create Entry
                </button>
              </form>
              <button
                onClick={getFunctionResult}
                className="mt-10 w-full bg-green-500 text-white p-2 rounded-lg hover:bg-green-600 transition"
              >
                Check List
              </button>
              <div className="mt-4">
                {result === "" ? (
                  <p>Checking...</p>
                ) : (
                  <p className="text-gray-700">
                    List Content: {result}
                  </p>
                )}
              </div>
            </div>
          </div>
        ) : (
          <CardHeader>
            <CardTitle>To get started, connect a wallet</CardTitle>
          </CardHeader>
        )}
      </div>
    </>
  );
}

export default App;

With this the get function is successfully integrated.

Integrating Aptos Move contracts can be a bit complex, but it is manageable with the right tools and approach. So you are in the right place, this will make it easier to integrate Move contracts.

Last updated