5


I wrote some code to get the current user groups by CSOM.

function getCurrentUser() {
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    clientContext.load(allGroups);
    this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededUser), Function.createDelegate(this, this.onQueryFailedUser));
}
function onQuerySucceededUser() {
    //debugger;
    var groups = currentUser.get_groups();
    var groupsEnum = groups.getEnumerator();
    while (groupsEnum.moveNext()) {
        //handle group
    }
}

But I get this error:

The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

on this line: groups.getEnumerator();
How can I solve it?

2 Answers 2

6

Move this line

var groups = currentUser.get_groups();

To your getCurrentUser method and make sure to load it

this.clientContext.load(groups);

before executing the request, this way you will have it loaded in your success-function

4
The code should look like this:

    function getCurrentUser() {
        this.clientContext = new SP.ClientContext.get_current();
        this.oWeb = clientContext.get_web();
        currentUser = this.oWeb.get_currentUser();
        this.allGroups = currentUser.get_groups();    
        clientContext.load(allGroups);
        this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededUser), Function.createDelegate(this, this.onQueryFailedUser));
    }
    function onQuerySucceededUser() {
        var groupsEnum = allGroups.getEnumerator();
        while (groupsEnum.moveNext()) {

        //handle group
        var group = groupsEnum.get_current();
        }
    }
1
  • 1
    Could y please add the line: var group = groupsEnum.get_current(); I lost 1 hout into this
    – XristosK
    Commented Jan 30, 2020 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.