Using JSON to display a username Answered

Post author
Joseph Lewis

Hi everyone, this is definitely a newbie question but I can't seem to get my json to display on my site. I'm using ms-data-json="username" to try and show a username, as explained in https://docs.memberstack.com/hc/en-us/articles/15719004543643-Using-Member-JSON-Data-with-Memberstack-s-DOM-Package, but it just won't work. The only json in my test member is {
"username": "josh"
}

Comments

2 comments

  • Comment author
    A J

    Hey Joseph Lewis, was testing the code mentioned in the article to see and faced the same issue of nothing being visible when I access the username from my personal JSON.

    So while the <div ms-data-json="username"></div> can be kept as it is.

    I have made some changes in the script as to how we fetch the information to this element. Please use this code and check if you are able to retrieve your username. I tested it in my personal workspace and it renders the data perfectly.

    <script>
    document.addEventListener("DOMContentLoaded", async function() {
    // shortens reference to Memberstack
    const memberstack = window.$memberstackDom;

    memberstack.getCurrentMember().then(async ({ data: member }) => {
    // if the member is logged in
    if(member) {
    // Get current member's JSON
    let memberJson = await memberstack.getMemberJSON();
    // Find all elements with the ms-data-json attribute
    const dataElements = document.querySelectorAll('[ms-data-json]');
    // Loop through the elements and add the member data
    dataElements.forEach(el => {
    // Get the key from the attribute
    const key = el.getAttribute('ms-data-json');
    // Check if the member data has this key
    if (memberJson.data.hasOwnProperty(key)) {
    // Add the corresponding member data to the element
    el.innerText = memberJson.data[key];
    }
    });
    }
    })
    });
    </script>

    Hope this helps

    0
  • Comment author
    Joseph Lewis

    Absolute lifesaver. Thank you!!!

    0

Please sign in to leave a comment.