Moralis.User.current() returns null , no userdata

Hi,

window.web3 = await Moralis.Web3.enable(); -> no error
await Moralis.Web3.authenticate(); -> no error .
Then after user = await Moralis.User.current();
I get as user object:
afbeelding

Showing record count is 0 , so no user data like username fetched.

If i look at Moralis dashboard -> Browser -> user : it shows 1 record !

Why can i not fetch data?

Moralis.initialize and serverUrl are set ok, and i am logged in to Moralis and to Metamask…

Full console.log…

===
If I run this example tutorial:
https://docs.moralis.io/guides/build-a-simple-dapp-in-3-mins-cloud-functions-part-5
then i get NO getAvgGas results (while there are transactions in via Metamask linked ganache):
{result: []}
I get a json object ! So communication is ok, but the cloud function “getAvgGas” internally fetches NO data.

Same as above user situation.
It seems I get no data by Moralis itself… for any (test or example tutorial) i run…! :frowning:

@ivan or @filip what can be the reason??

1 Like

Login seems to work as you get back id in the user Object you print.

  1. Do you see transactions in your EthTransactions table in the database?
  2. Can you post exact cloud function for getAvgGas?
  3. Also post your server URL so the team can check your server.

Thanks

Please post more details of your code and setup.

You mention using Ganache. Have you followed the guides for setting up Moralis to connect to Ganache?
https://docs.moralis.io/guides/setting-up-ganache

  • When you created your Moralis Server instance did you select the “Local Dev Chain” network?
  • Have you installed frp and modified frpc.ini with the settings from “View Details > Devchain Proxy Server > Ganache”?
  • Is Ganache running? Is frpc running and connected? (the server should say “Status: Connected”)

Does it work if you create a new server on mainnet or ropsten?

Ivan, thanks for reply!

  1. If you mean to have an existing EthTransactions table inside the created server’s Dashboard at Moralis.io: no does not exist, only a EthAddress table. I cannot find a direction to create the EthTransactions table and indeed that one is mentioned in the code to copy into the “Cloud Functions” page (see 2.) and mentioned in Part3 to read…


    I guessed the linked Metamask was used to deleiver these transactions, but can imagine now(!) that the tutorial wants to read the (a) EthTransactions table of the Moralis server :wink:

  2. (may be not important any more, but here it is:)

  3. https://03uqj0cfwji7.moralis.io:2053/server

Reagrds,
Cas

Hi Mayer,

Thanks for response!

Yes i did follow the steps for Moralis to connect to Ganache with Metamask: settings as follows:


Metamasks is set to this network and shows the Ether amount of the imported Address.

And yes as 3th selection the “Local Dev Chain” is selected
afbeelding

I have installed frp, but is that one to be run for the local blockchain of Ganache , since it is linked via (by) Metamask? I understood frp is needed if i want to directly link Gamache to Moralis-server and now Metamasks services this…
I know the Moralis server Details tab “Devchain Proxy Server” and how to set it up for frp. If that is needed besides the Metamask seetup :wink:

Ganache is running (o.c.). But the frp not… I know how to arrange !

But that should solves it for the example tutorial !

I used that to underline i get no data from the Moralis server, with a correct connection, since i get an empty json response: {result: []}
for the call:
const user = await Moralis.User.current();
While there is a User table inside the used seerver…

Regards,
Cas

Without frp running the Moralis Server cannot connect to your local ganache dev chain. frp serves as a bridge (proxy) between your local environment and the server. Please see Ivan’s 2nd video on “Connecting Ganache to Moralis” in the guide linked above.

This is why the guide recommends using mainnet to get started quickly. It’s much less setup. Signing messages to authenticate does not cost gas, so no need to worry about that.

understood for ganache link.

But what about no data with : const user = await Moralis.User.current();
See 1st message for outputs.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
	<title>Morarible NWK</title>

	<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js" type="text/javascript"></script>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
	<script src="https://unpkg.com/moralis/dist/moralis.js" type="text/javascript"></script>
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

	<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
	<link href="./style.css" rel="stylesheet">
</head>
<body>

	<div>
		<button id="btnConnect">Connect wallet</button>
		<button id="btnUserInfo">Profile</button> 
	</div>	

	<div id="userInfo">
		<h4>User Profile</h4>
		<input type="text" id="txtUsername" required="true" placeholder="Enter username">
		<input type="text" id="txtEmail" placeholder="Enter email">	<small>Optional</small>
		<img width="50" height="50" src="" id="imgAvatar" alt="">
		<label for="fileAvatar">Select avatar (jpg!)</label>
		<input type="file" id="fileAvatar">
		<button id="btnLogout">Log out</button>
		<button id="btnCloseUserInfo">Close</button>
		<button id="btnSaveUserInfo">Save</button>
		
	</div>
	
    <script type="text/javascript" src="./main.js"></script>
</body>
</html>

main.js

Moralis.initialize("4atV9qZWzbz647UcMECrkbhShGd4gFeZuo223B3y"); // Application id from moralis.io
Moralis.serverURL = "https://03uqj0cfwji7.moralis.io:2053/server"; //Server url from moralis.io

const userConnectButton = document.getElementById("btnConnect");
const userProfileButton = document.getElementById("btnUserInfo");
const userInfo = document.getElementById("userInfo");

const userUsernameField = document.getElementById("txtusername");
const userEmailField = document.getElementById("txtEmail");
const userAvatarImg = document.getElementById("imgAvatar");
const userAvatarFile = document.getElementById("fileAvatar");

hideElement = (element) => element.style.display = "none";
showElement = (element) => element.style.display = "block";

initUser = async () => {
	console.log("init User");
	const user = await Moralis.User.current();
	if (user) {
		console.log("init User is current");
		console.log(user);
		hideElement(userConnectButton);
		showElement(userProfileButton);
	} else {
		console.log("init User not current");
		showElement(userConnectButton);
		hideElement(userProfileButton);	
	}
}

login = async () => {
	console.log("login");
	try {
		await Moralis.Web3.authenticate();
		initUser();
	} catch(error) {
		alert(error);
	}
}

logout = async () => {
	console.log("logout");
	await Moralis.User.logOut();
	hideElement(userInfo);
	initUser();
}

openUserInfo = async () => {
	console.log("Open user info");
	const user = await Moralis.User.current();
	console.log(user)
	if (user) {
		userEmailField.value = (user.get('email') ?? ""); // not undefined
		userUsernameField.value = user.get('username');
		const userAvatar = user.get('avatar');
		if (userAvatar) {
			userAvatarImg.src = userAvatar.url();
			showElement(userAvatarImg);
		} else {
			hideElement(userAvatarImg);
		}

		showElement(userInfo);
	} else {
		login();
	}
}

saveUserInfo = async () => {
	user.set('username', userUsernameField.value); // throws error for duplicates..!
	user.set('email', userEmailField.value);
	if (userAvatarFile.files.length > 0) {
		const avatar = new Moralis.File("avatar.jpg", userAvatarFile.files[0]); // simple only for jpg..
		user.set('avatar', avatar);
	}
	await user.save();
	alert("User info saved successfully!");
	openUserInfo();
}


init = async () => {
	console.log("init");
	hideElement(userInfo);
	window.web3 = await Moralis.Web3.enable();
	initUser();
}

userConnectButton.onclick = login;
userProfileButton.onclick = openUserInfo;
document.getElementById("btnCloseUserInfo").onclick = () => hideElement(userInfo);
document.getElementById("btnLogout").onclick = logout;
document.getElementById("btnSaveUserInfo").onclick = saveUserInfo;
init();

So I ran your code against one of my Moralis ganache instances.

  • Calling Moralis.Web3.enable() asks the user to connect their wallet and returns a web3 instance. This does not authenticate the user in Moralis.
  • Calling Moralis.Web3.authenticate() asks the user to sign a message. This proves they have access to to the private key that controls the address they are logging in with. This returns a user object
  • Now that the user has been authenticated Moralis.User.current() will return the currently authenticated user (or null if no user is logged in)

See the screen shot below and the output. Note the modifications I made to the code. The left hand terminal instance in VS Code is running ganache-cli and the right is running frp.

Cheers.

Sorry! Indeed you get the user object, but with “_objCount: 0”
I get the same and then the user object has empty data, so no data retrieved from The Moralis server…

How to solve this?
This should be the end of “I cloned rarible in 24H - Saving User Profiles [Part 3]” -> I do nog get the (11:27) shown User Profile and form fields lines …!
@Capplequoppe - can you update here?

I have "./frpc.exe -c ./frpc.ini " running and that results in a few more tables in the server instance… :wink:

Did you add await Moralis.Web3.authenticate()? I changed your code by adding this. As I mentioned before calling authenticate is required to log in the user, just calling enable is not enough. The _objCount: 0 thing is nothing to worry about. You should see a property called attributes on the user object. See below.

initUser = async () => {
	console.log("init User");
	const user = await Moralis.User.current();
  console.log("initUser: current:", user);

	if (user) {
		console.log("user is already authenticated");
		console.log(user);
		hideElement(userConnectButton);
		showElement(userProfileButton);
	} else {
    console.log("ask user to sign message to authenticate")

     // *** Added call to authenticate ***
    const user = await Moralis.Web3.authenticate();
    console.log("authenticated user:", user);

    const currentUser = Moralis.User.current();
    console.log("current user:", currentUser);

		showElement(userConnectButton);
		hideElement(userProfileButton);	
	}
}

If you’re still having trouble after adding the call to await Moralis.Web3.authenticate(), then try creating a new Moralis server and see if a shiney fresh instance makes a difference (perhaps the old one became corrupted).

Ok, coming closer…
In previous post I had indeed added the authenticated() call… (complete main.js)

Moralis.initialize("vhR4GZ2i8OuLrZz5yNm7FX77sh8VG9VFT4DBtE6O"); // Application id from moralis.io
Moralis.serverURL = "https://lscfractqgvk.moralis.io:2053/server"; //Server url from moralis.io

const userConnectButton = document.getElementById("btnConnect");
const userProfileButton = document.getElementById("btnUserInfo");
const userInfo = document.getElementById("userInfo");

const userUsernameField = document.getElementById("txtusername");
const userEmailField = document.getElementById("txtEmail");
const userAvatarImg = document.getElementById("imgAvatar");
const userAvatarFile = document.getElementById("fileAvatar");

hideElement = (element) => element.style.display = "none";
showElement = (element) => element.style.display = "block";

initUser = async () => {
	console.log("initUser: start");
	const user = await Moralis.User.current();
	console.log("initUser: current=", user);
	if (user) {
		console.log("initUser: user is already authenticated");
		console.log(user);
		hideElement(userConnectButton);
		showElement(userProfileButton);
	} else {
		console.log("initUser: ask user to sign message to authenticate");
		const user = await Moralis.Web3.authenticate();
		console.log("initUser: authenticated user=", user);
		const currentUser = Moralis.User.current();
		console.log("initUser: current=", currentUser);
		showElement(userConnectButton);
		hideElement(userProfileButton);	
	}
}

login = async () => {
	console.log("login");
	try {
		await Moralis.Web3.authenticate();
		initUser();
	} catch(error) {
		alert(error);
	}
}

logout = async () => {
	console.log("logout");
	await Moralis.User.logOut();
	hideElement(userInfo);
	initUser();
}

openUserInfo = async () => {
	console.log("Open user info");
	const user = await Moralis.User.current();
	console.log(user)
	if (user) {
		userEmailField.value = (user.get('email') ?? ""); // not undefined
		userUsernameField.value = user.get('username');
		const userAvatar = user.get('avatar');
		if (userAvatar) {
			userAvatarImg.src = userAvatar.url();
			showElement(userAvatarImg);
		} else {
			hideElement(userAvatarImg);
		}

		showElement(userInfo);
	} else {
		login();
	}
}

saveUserInfo = async () => {
	user.set('username', userUsernameField.value); // throws error for duplicates..!
	user.set('email', userEmailField.value);
	if (userAvatarFile.files.length > 0) {
		const avatar = new Moralis.File("avatar.jpg", userAvatarFile.files[0]); // simple only for jpg..
		user.set('avatar', avatar);
	}
	await user.save();
	alert("User info saved successfully!");
	openUserInfo();
}


init = async () => {
	console.log("init");
	hideElement(userInfo);
	window.web3 = await Moralis.Web3.enable();
	initUser();
}

userConnectButton.onclick = login;
userProfileButton.onclick = openUserInfo;
document.getElementById("btnCloseUserInfo").onclick = () => hideElement(userInfo);
document.getElementById("btnLogout").onclick = logout;
document.getElementById("btnSaveUserInfo").onclick = saveUserInfo;
init();

and with a new server i get : “_objCount: 1” after that authentication (!)
and the id has the value of the objectId of the user record in servers Dashboard!

But… username is still empty… (not in Dasboards user record.

Console output…

I see inside initUser: always true part is taken, since we have a valid user object (!), but only Id is filled, not the other fields…

So the “Moralis.Web3.authenticate();” never called…

If i change initUser to

initUser = async () => {
	console.log("initUser: start");
	var user = await Moralis.User.current();
	console.log("initUser: 1 current=", user);
	user = await Moralis.Web3.authenticate();
	console.log("initUser: 2 current=", user);
	if (user) {
		console.log("initUser: user is already authenticated");
		console.log(user);
		hideElement(userConnectButton);
		showElement(userProfileButton);
	} else {
		console.log("initUser: ask user to sign message to authenticate");
		 user = await Moralis.Web3.authenticate();
		console.log("initUser: authenticated user=", user);
		const currentUser = Moralis.User.current();
		console.log("initUser: current=", currentUser);
		showElement(userConnectButton);
		hideElement(userProfileButton);	
	}
}

The authentication is done, but still no data…

Continueing find out what’s still wrong… ?!

1 Like

Previous was with FireFox browser…

If I use the Chrome browser I see the data in the object, BUT user.get() not…

The code:

Moralis.initialize("vhR4GZ2i8OuLrZz5yNm7FX77sh8VG9VFT4DBtE6O"); // Application id from moralis.io
Moralis.serverURL = "https://lscfractqgvk.moralis.io:2053/server"; //Server url from moralis.io

const userConnectButton = document.getElementById("btnConnect");
const userProfileButton = document.getElementById("btnUserInfo");
const userInfo = document.getElementById("userInfo");

const userUsernameField = document.getElementById("txtusername");
const userEmailField = document.getElementById("txtEmail");
const userAvatarImg = document.getElementById("imgAvatar");
const userAvatarFile = document.getElementById("fileAvatar");

hideElement = (element) => element.style.display = "none";
showElement = (element) => element.style.display = "block";

initUser = async () => {
	console.log("initUser: start");
	var user = await Moralis.User.current();
	console.log("initUser: 1 current=", user);
	user = await Moralis.Web3.authenticate();
	console.log("initUser: 2 current=", user);
	if (user) {
		console.log("initUser: user is already authenticated");
		console.log(user);
		hideElement(userConnectButton);
		showElement(userProfileButton);
	} else {
		console.log("initUser: ask user to sign message to authenticate");
		 user = await Moralis.Web3.authenticate();
		console.log("initUser: authenticated user=", user);
		const currentUser = Moralis.User.current();
		console.log("initUser: current=", currentUser);
		showElement(userConnectButton);
		hideElement(userProfileButton);	
	}
}

login = async () => {
	console.log("login");
	try {
		await Moralis.Web3.authenticate();
		initUser();
	} catch(error) {
		alert(error);
	}
}

logout = async () => {
	console.log("logout");
	await Moralis.User.logOut();
	hideElement(userInfo);
	initUser();
}

openUserInfo = async () => {
	console.log("Open user info");
	const user = await Moralis.User.current();
	console.log(user)
	if (user) {
		userEmailField.value = (user.get('email') ?? ""); // not undefined
		console.log("email=" + userEmailField.value);
		userUsernameField.value = user.get('username');
		console.log("username=" + userUsernameField.value);
		const userAvatar = user.get('avatar');
		if (userAvatar) {
			userAvatarImg.src = userAvatar.url();
			showElement(userAvatarImg);
		} else {
			hideElement(userAvatarImg);
		}

		showElement(userInfo);
	} else {
		login();
	}
}

saveUserInfo = async () => {
	user.set('username', userUsernameField.value); // throws error for duplicates..!
	user.set('email', userEmailField.value);
	if (userAvatarFile.files.length > 0) {
		const avatar = new Moralis.File("avatar.jpg", userAvatarFile.files[0]); // simple only for jpg..
		user.set('avatar', avatar);
	}
	await user.save();
	alert("User info saved successfully!");
	openUserInfo();
}


init = async () => {
	console.log("init");
	hideElement(userInfo);
	window.web3 = await Moralis.Web3.enable();
	initUser();
}

userConnectButton.onclick = login;
userProfileButton.onclick = openUserInfo;
document.getElementById("btnCloseUserInfo").onclick = () => hideElement(userInfo);
document.getElementById("btnLogout").onclick = logout;
document.getElementById("btnSaveUserInfo").onclick = saveUserInfo;
init();

So step-by-step… any help??

SOLVED !

Typo:
const userUsernameField = document.getElementById(“txtusername”);
must be
const userUsernameField = document.getElementById(“txtUsername”);
with txtUsername with capital U …!

And I use the Firefox browser… which shows the user object more explicit, I had to look to:
prototype -> <prototype> -> <prototype> -> attributes
to find the username value !!

The Chromebrowser directly shows the attributes subobject with the values.

With corrected typo and code cleanup , the code is as in tutorial (small improvement in openUserInfo() by using the ?? .

Moralis.initialize("7zCudvpT22yhFk2IwUAvAnX2hBmxJVd9psqS1zrq"); // Application id from moralis.io
Moralis.serverURL = "https://jctpsxzwr8jg.moralis.io:2053/server"; //Server url from moralis.io

const userConnectButton = document.getElementById("btnConnect");
const userProfileButton = document.getElementById("btnUserInfo");
const userInfo = document.getElementById("userInfo");

const userUsernameField = document.getElementById("txtUsername");
const userEmailField = document.getElementById("txtEmail");
const userAvatarImg = document.getElementById("imgAvatar");
const userAvatarFile = document.getElementById("fileAvatar");

hideElement = (element) => element.style.display = "none";
showElement = (element) => element.style.display = "block";

initUser = async () => {
	console.log("initUser: start");
	var user = await Moralis.User.current();
	if (user) {
		console.log("initUser: user is already authenticated:", user);
		hideElement(userConnectButton);
		showElement(userProfileButton);
	} else {
		console.log("initUser: ask user to sign message to authenticate: ", user);
		user = await Moralis.Web3.authenticate();
		console.log("initUser: authenticated user=", user);
		showElement(userConnectButton);
		hideElement(userProfileButton);	
	}
}

login = async () => {
	console.log("login");
	try {
		await Moralis.Web3.authenticate();
		initUser();
	} catch(error) {
		alert(error);
	}
}

logout = async () => {
	console.log("logout");
	await Moralis.User.logOut();
	hideElement(userInfo);
	initUser();
}

openUserInfo = async () => {
	console.log("Open user info");
	const user = await Moralis.User.current();
	console.log(user)
	if (user) {
		userEmailField.value = (user.get('email') ?? ""); // not undefined
		console.log("email=" + userEmailField.value);

		userUsernameField.value = user.get('username');
		console.log("username=" + userUsernameField.value);

		const userAvatar = user.get('avatar');
		if (userAvatar) {
			userAvatarImg.src = userAvatar.url();
			showElement(userAvatarImg);
		} else {
			hideElement(userAvatarImg);
		}

		showElement(userInfo);
	} else {
		login();
	}
}

saveUserInfo = async () => {
	user.set('username', userUsernameField.value); // throws error for duplicates..!
	user.set('email', userEmailField.value);
	if (userAvatarFile.files.length > 0) {
		const avatar = new Moralis.File("avatar.jpg", userAvatarFile.files[0]); // simple only for jpg..
		user.set('avatar', avatar);
	}
	await user.save();
	alert("User info saved successfully!");
	openUserInfo();
}


init = async () => {
	console.log("init");
	hideElement(userInfo);
	window.web3 = await Moralis.Web3.enable();
	initUser();
}

userConnectButton.onclick = login;
userProfileButton.onclick = openUserInfo;
document.getElementById("btnCloseUserInfo").onclick = () => hideElement(userInfo);
document.getElementById("btnLogout").onclick = logout;
document.getElementById("btnSaveUserInfo").onclick = saveUserInfo;
init();

Thanks.

3 Likes

Glad you got it working! :partying_face:

1 Like