Execute a function within useEffect continuously until the contract is fully loaded

When I make the call contract?.methods.name().call() within the same scope as loading providers, everything works perfectly fine. It also works fine when I do a page reload.

However, if I make the call contract?.methods.name().call() in another useEffect, I encounter an error stating 'Cannot read properties of undefined (reading 'methods')' when I do a page reload. It appears that this function is being called before the contract is fully loaded or available on the server side, especially since I am using Next.js

Is there a way for me to resolve this issue and still be able to make the call contract?.methods.name().call() in another useEffect and during a page reload? Is that even feasible? Below is the code snippet. Thank you

const Demo = (props: Props) => {
  const [web3Api, setWeb3Api] = useState<{
    web3: Web3 | undefined;
    isProviderLoaded: boolean;
    provider: any;
    contract: any;
    name: string;
  }>({
    isProviderLoaded: false,
    web3: undefined,
    provider: undefined,
    contract: undefined,
    name: "",
  });
  const [contractName, setContractName] = useState<string>("");

  const loadProvider = async () => {
    const provider = await detectEthereumProvider();
    const web3 = new Web3(provider as any);

    if (provider) {
      const contract = await loadContract("Demo", web3);
      const name = await contract?.methods.name().call();
      setWeb3Api({
        web3,
        provider,
        contract,
        isProviderLoaded: true,
        name,
      });
    }
  };

  useEffect(() => {
    const getContractName = async () => {
      // todo Cannot read properties of undefined (reading 'methods')
      const contractName = await web3Api.contract.methods.name().call();
      setContractName(contractName);
    };
    getContractName();
  }, [web3Api]);

  useEffect(() => {
    loadProvider();
  }, []);

  return (
    <Layout>
      <p>Demo</p>
      {/* Work OK */}
      <p>{web3Api.name}</p>
      {/* Not OK */}
      <p>{contractName}</p>
    </Layout>
  );
};

export default Demo;

Answer №1

  useEffect(() => {
    const fetchContractName = async () => {
      const name = await web3Api.contract.methods.name().call();
      updateContractName(name);
    };
    web3Api.contract && fetchContractName();
  }, [web3Api.contract]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve a converted document using the Microsoft Graph API

I'm encountering an issue when trying to save a PDF file received from the Microsoft Graph API. The call I am making looks like this: const convertConfig = { headers: { Authorization: <my token> } }; convertConfig.headers['C ...

Steps to show an input button and exit the current window

I am looking for guidance on how to enable or display an input on a webpage if an ajax call is successful. I want this input, when clicked, to be able to close the current window using JavaScript. What would be the most efficient way to accomplish this? B ...

Leveraging the Scroll feature in Bootstrap for smooth scrolling

Seeking assistance with implementing scroll in Bootstrap 5 on my child component (ProductList.vue). Can anyone guide me on how to integrate the code? I have been searching for a solution without success. Below is the Bootstrap 5 code on the child component ...

When accessing the AWS Elasticache Config Endpoint, the response states: "ERROR: WRITE ACCESS DENIED - This replica is read-only and does not allow write operations."

Just to clarify, I am a beginner when it comes to redis and elasticache. You can find an answer to my question on this stackoverflow post here. I currently have a simple AWS ElastiCache Redis cluster setup: 3 shards, 9 nodes encryption enabled for data a ...

Packages required for plugins on Npm

I am fairly new to NPM dependencies and I'm currently transitioning from the Ruby world. Working on a Chrome extension utilizing React, in my content.js script, I have the following code at the top: var React = require("react"); var $ = require("jqu ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

The Angular Factory service is accurately retrieving data, but unfortunately, it is not being displayed on the user interface

Here is a link to the complete source code angular .module('app') .factory('Friends', ['$http',function($http){ return { get: function(){ return $http.get('api/friends.json') .t ...

Issues related to validation prior to submission

Having trouble with a VeeValidate example from the documentation. The example can be found here. I seem to be missing something crucial but can't figure out what it is. For some reason, my form always validates as valid, even when no text is entered ...

Reload a single php page by utilizing a different page

Whenever I click on a button on my PHP page (dashboard.php), it opens a pop-up page (viewstatus.php). On this pop-up page, I update some data and then click the submit button. However, after submitting the data, the pop-up should close and the dashboard. ...

Selective Circle Appending Techniques

I am having some issues with my bubble chart code. The data file I am working with contains instances where the GDPperCapita and/or LifeExpectancy values are either 0 or NaN, causing problems when appending circles to the chart. I would like to know if th ...

Invoking the HTML method from a WCF service

Currently, I am utilizing a callback in my WCF service to receive raw frames from the camera. I am currently working on developing an HTML application that will showcase these frames. However, my current approach involves using a button click event in HTM ...

Always ensure that the state is correctly updated before displaying any information in a React Modal component

I am currently utilizing a combination of Material-UI components, the useState hook, and the NextJS framework. Within my render method, I am mapping over someData where each element has the following structure: someData[i] : { "id": number, ...

Guide to Sending and Scheduling Notifications through HTML 5's Notification Web APIs

Is it possible to utilize Web APIs to Schedule Notifications and send them at specific times? I am working on a CMS application that allows users to schedule and send push notifications for their mobile apps. I am interested in implementing something sim ...

Tips for restricting function invocations in JavaScript?

I am seeking a function called limitCalls(fn, maxCalls) which accepts a function fn and creates a new function that can only be called the specified number of times in maxCalls. Here is a test example: it('limitCalls', () => { const makeIncre ...

HTML Canvas resizing challenge

My goal is to resize the canvas to fit inside its parent div within a Bootstrap grid, but I'm running into an issue where the canvas keeps expanding to 2000px x 2000px. Despite successfully resizing based on console.log outputs showing the same dimens ...

Tips for structuring a search query before sending it to a NodeJS server using mongoose

As I work on my new app, there's a date input field that I'm developing. The goal is to use it for searching the appointments collection based on a specific date. On the server side, all dates are handled in UTC format. Here's how the sear ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...

How to use JQuery UI sortable to automatically scroll to the bottom of the page

Having trouble with a few sortable tables and here is how I initialized the sortable object: var options = { helper: customHelper, handle: ".moveTargetDeliverables", containment: "#fieldset_deliverables_summary", tolerance: 'pointer&a ...

Error: 'require' is not recognized as a valid command - Node.js

I recently attempted to integrate the d3-gauge plugin into a basic node.js/express server. Following the default directory structure generated by Express, I organized the files from the 'example' folder as follows: . ├── app.js ├── b ...

Highcharts 3D Pie Chart with Drilldown Feature

How can I create a 3D Pie Chart with Drilldown effect? I am having trouble understanding how it works. Here is a JsFiddle Demo for a 3D Pie Chart: JsFiddle Demo And here is a JsFiddle Demo for a 2D Pie Chart with Drilldown feature: JsFiddle Demo You can ...