Getting Member Information - SPA

Specific examples of how to use the Javascript API.

In fronted environments such as single page applications, like React, Angular or Vue, the use of Events will not work as needed because MemberSpace will only fire the .ready event when initialized. For reliable access to memberInfo use the following Promise function that incorporates a few different components of the MemberSapce JavaScript API.

const getMsReadyPromise = () =>
  new Promise(resolve => {
    if (MemberSpace.ready) {
      // Ready event is already fired, so let's not wait for it, it will not be fired again
      resolve(window.MemberSpace.getMemberInfo());
    } else {
      // MS widget is not yet ready, let's subscribe for the event
      const handleReady = ({ detail }) => {
        resolve(detail);
        // Unsubscribe ourselves, this allows GC to collect all related memory
        document.removeEventListener('MemberSpace.ready', handleReady);
      };

      // Listen to ready event
      document.addEventListener('MemberSpace.ready', handleReady);
    }
  });

// ... Somewhere in an async fn
const { memberInfo } = await getMsReadyPromise();

// ... or using Promise.then
getMsReadyPromise().then(({ memberInfo }) => {
  // your code here
});

This is very useful when you need this information only in specific screens or specific components in frameworks such as React, Angular and Vue.

Last updated