Home > OS >  .then() is not returning a promise
.then() is not returning a promise

Time:04-10

I am trying to import a function from another file and while rendering in the react component, it doesn't get rendered. The value of that variable is showing undefined

index.js

const GetOwnBalance = async () => {
    if (!isInitialized) {
        await init();
    }
    // const web2 = new Web3(provider);
    nftContract.methods
    .getBalance(selectedAccount)
        .call()
        .then((balance) => {
            // console.log(`Balance of ${selectedAccount} is ${balance}`);
            console.log("Intermediate balance : "   balance);
            // return balance;
        }   
    );
};
export default GetOwnBalance;

Until this everything runs perfect, but the problem is in App.js

App.js

import React, { useState } from 'react';
import  GetOwnBalance  from './index';

function App() {
    const [balance, setBalance] = useState(0);
    function fetchBalance() {
        GetOwnBalance()
            .then(value => {
                setBalance(value); //value shows undefined ???
                console.log("Final Balance : "   value);
            }
                
            );
    }

    return (
        <div className="App">
            <p>Your balance is {balance}</p>
            <button onClick={fetchBalance}>Refresh balance</button>
        </div>
    );
}

export default App;

When I try to run this piece of code, the value value in the .then() promise shows undefined. Can someone please explain why is it so?

CodePudding user response:

It is because you are not returning anything from function GetOwnBalance.

Try adding the return keyword in return nftContract.methods....

const GetOwnBalance = async () => {
    if (!isInitialized) {
        await init();
    }
    // const web2 = new Web3(provider);
   return nftContract.methods
    .getBalance(selectedAccount)
        .call()
        .then((balance) => {
            // console.log(`Balance of ${selectedAccount} is ${balance}`);
            console.log("Intermediate balance : "   balance);
            // return balance; <-- Also uncomment this
        }   
    );
};
export default GetOwnBalance;

CodePudding user response:

Is the "GetOwnBalance" function located at index.js or ./Web3Client'?

Instead of "value" parameter on

 .then(value => {
            setBalance(balance); //value shows undefined ???
            console.log("Final Balance : "   balance);
        }

Try just using the hook value name:

 .then(() => {
            setBalance(value);
            console.log("Final Balance : "   value);
        })

Additionally you don't have to set "GetOwnBalance" as async if you don't use await

  • Related