Search code examples
mixpanel

Waiting for mixpanel JS lib to be ready so I can get users distinct_id


We want to use MixPanel to capture events on our site and I'm trying to get hold of the users distinct id, so I'm using the following code snippet:

$(document).ready(function($){  
    console.log("We have distinct id");
    console.log(mixpanel.get_distinct_id());
});

This causes an error saying 'undefined is not a function' when attempting to get the distinct id.

I've checked in the debugger and can confirm that the mixpanel object does not have a get_distinct_id method, However if I wait until the page has loaded and then evaluate mixpanel.get_distinct_id() in the console, I get the distinct id without problem.

I can only guess that the mixpanel object hasn't completed initialisation yet. Is there a callback or an event that I can use to know once the mixpanel object will be able to tell me the users distinct_id?


Solution

  • From a Mixpanel article:

    "[...] pass a config object to the mixpanel.init() method with a loaded parameter and a callback function that will execute immediately after our library has finished loading. Inside the callback function, you can use the get_property() and get_distinct_id() methods and ensure that they'll only execute after the library has finished loading."

    mixpanel.init('Project Token', {'loaded':function() {
        var distinct_id = mixpanel.get_distinct_id()}
    });
    

    Source: How to prevent get_distinct_id & get_property from returning undefined