How to get the logged in user's ID and other details

I am trying to edit the user’s password in a React app. This is fine, if I have the user’s ID/reference number, but how do I go about getting this number in the first place? Currently whilst playing about I am simply retrieving it manually from the database.

My user is logged in fine, and I am caching their secret key in order to keep them logged in if they refresh the page etc. So when a user returns, I am connecting like this:

var client = new faunadb.Client({ secret: userSecret });

My edit password code is like this:

client.query(
  q.Update(q.Ref(q.Collection('users'), 'xxxxxxxxxxxxxxxxxx'), {
    credentials: { password: 'password' }
  })
)

But how do I get the ID in the first place? Should I have also cached and made a note of something when I logged in?

Same goes for any other data saved when creating the user, such as an email address that they signed up with. I would assume there’s an easy way to retrieve the current user’s data, but if not would guess that I’ll need the ID above in order to query their data.

Thanks for your help!

Hi @alexb148,

If you are using Tokes, Identity() returns the Ref for the logged-in user.

> Identity()
Ref(Collection("Users"), "275547972759979527")

you can use in one shot:

Update(Identity(), {credentials: { password: 'password' })

Hope this help

Luigi

2 Likes

fyi, there are quite some example that can be found in the repository linked to this article: https://css-tricks.com/rethinking-twitter-as-a-serverless-app/

It has examples of many resources that are created and immediately linked to users via the Identity() function.

2 Likes

@Luigi_Servini thank you, this was helpful and has solved the issue of fetching the user’s identity.

For reference, my working js code now looks like this:

client.query(
  q.Update(q.Identity(), {
    credentials: { password: 'newPassword' }
  })
)
2 Likes

@databrecht thank you, I had scoured this repo a few times but it’s not always easy working out exactly what each line of code does.

However, with a little more reading and experimentation I have successfully established that I can read any data associated with the currently logged in user with the following JS code, where “email” is the data I’m looking for:

q.Select(['data', 'email'], q.Get(q.Identity()))

and I can also get the logged in user’s reference object using:

q.Select(['ref'], q.Get(q.Identity()))

This is helping me make good progress with my learning!

Identity() is the Ref. Get-ing and then Select-ing the ref will only cost an exra read op.

This is proved by the update function working, since it accepts the user document Ref.

Update(
  Identity(),  // <-- User document Ref right here.
  {credentials: { password: 'password' }
)
4 Likes

@ptpaterson ah I see, I saw it written like that somewhere along the way, but that makes sense - thanks for highlighting this!

3 Likes