1

I am new to SPFx and wrapping my head around getting the current logged in user on SPFx using React , I did refer to a few posts here , However couldn't find the resolution I've been looking for.

My end goal is to get the current logged in userID and store the value in a variable to be used in RestAPI later

Below is the code sample

public componentdidmount() {
  var u;
  sp.web.currentUser.get().then(
    (user) => {
      console.log(user);
      u = user.UserId;
    },
    (errorResponse) => {
      debugger;
      console.log(errorResponse);
    }
  ); //Get Current User*/

  sp.web.lists
    .getByTitle("SampleList")
    .items.select(
      "*",
      "CourseName/Title",
      "Attendee/Title",
      "Attendee/ID",
      "Status/Title",
      "Completed",
      "AttachmentFiles"
    )
    .expand("CourseName", "Attendee", "Status", "AttachmentFiles")
    .filter("Status/Title eq 'Not Started' and Attendee eq '" + u + "'")
    .top(4999)
    .orderBy("Created", false)
    .get()
    .then((response) => {
      let getdetails = response.map((item) => new EntityListItems(item));
    });
}

While debugging , I get an undefined value on the variable u.

I would be grateful if someone could help me with storing the current logged in userID to a variable so that I can pass the value to the Rest call.

Any help would be appreciated.

Amos
  • 2,030
  • 1
  • 5
  • 9
Vivek
  • 61
  • 4
  • 16

2 Answers2

3

The request of getting user info is Asynchronous, it cannot promise the second request is called after the variable u has set a value. Hence we'd like to suggest you put the second request in the callback, this should make sure the user info has already been acquired.

And there is a quick method to get current user id:

this.context.pageContext.legacyPageContext["userId"]

legacyPageContext is similar to _spPageContextInfo. Refer to below blog to get more details:

BR

Baker_Kong
  • 1,739
  • 1
  • 4
  • 9
  • @Baker_King_MSFT Thank you for the response , I tried the step suggested by you and got the error "Cannot read property 'legacyPageContext' of undefined" I have set the context on webpart.ts file as shown below public onInit(): Promise { return super.onInit().then(_ => { // other init code may be present sp.setup({ spfxContext: this.context }); }); } – Vivek Aug 27 '20 at 13:24
0

I use this: this.context.pageContext.user.email

AaronBaker
  • 1,013
  • 11
  • 15