The account address is getting displayed on the console properly when initializing but showing undefined when calling console.log(account) from other functions. Here is my code.
var account;
window.addEventListener('load', async () => {
if (window.ethereum) {
window.web3 = new Web3(ethereum);
ethereum.autoRefreshOnNetworkChange = false;
const accounts = await ethereum.enable();
account = accounts[0];
console.log(account); //here the account working properly.
}
});
var contractaddress = '0x26708Df214A65Dda444E61266642e6650F4e8923';
function get_request_details() {
console.log(account); //here it is showing undefined
}
window.onload = get_request_details;
The problem was arising because the function was running before the initialization can be done and that is why I modified the code as follows.
var account;
window.addEventListener('load', async () => {
if (window.ethereum) {
window.web3 = new Web3(ethereum);
ethereum.autoRefreshOnNetworkChange = false;
const accounts = await ethereum.enable();
account = accounts[0];
console.log(account); //here the account working properly.
get_request_details();
}
});
var contractaddress = '0x26708Df214A65Dda444E61266642e6650F4e8923';
function get_request_details() {
console.log(account); //here it is also working
}
I called the function from the async event only so that when the initialization will be done after than only the function should run.
I don't see the contractaddress variable used anywhere. So here is my opinion.
const get_request_details = function(account) {
console.log(account);
}
const run_after_window_loaded = async function() {
if (!window.ethereum) {
return false;
}
window.web3 = new Web3(ethereum);
ethereum.autoRefreshOnNetworkChange = false;
const accounts = await ethereum.enable();
console.log(accounts);
if(accounts.length > 0){
get_request_details(accounts[0]);
}
}
window.addEventListener('DOMContentLoaded', async function(event) {
await run_after_window_loaded();
});