How to prevent get_distinct_id & get_property from returning undefined

Fixing the JavaScript error "TypeError: undefined is not a function"

The Mixpanel JavaScript library loads asynchronously to prevent the script from blocking other processes from running on your web application. Because of this, you might occasionally encounter an issue where you try to call mixpanel.get_distinct_id() or mixpanel.get_property() and get an error message:

    TypeError: undefined is not a function

...instead of a distinct_id or super property value from the cookie.

This error can sometimes appear intermittently, especially on slow connections, because these methods are not available until the Mixpanel library fully loads. All the other methods are available instantly through the stub function in our snippet.

To fix the error, 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.

Here's a small code snippet below that demonstrates the loaded callback:

   mixpanel.init('YOUR PROJECT TOKEN', {
    loaded: function(mixpanel) {
        distinct_id = mixpanel.get_distinct_id();
    }
});

If you have any further questions, don't hesitate to reach out to support@mixpanel.com.

Happy Mixpaneling!