Post-Login Action Not Setting App_Metadata

Problem statement

When attempting to set a user’s app_metadata in a Post-Login Action, the update doesn’t appear to be working, and the user profile does not have any metadata attached to the user’s profile.

Below is the code snippet that is attempting to set the app_metadata.

  fetch(path, options)
    .then((response) => {[...]
    }).then((body) => {      if ( <some condition>) {
        api.user.setAppMetadata("key", "value");
        return; }

What is the reason for this unexpected behavior, and how can it be resolved?

Symptoms

The user’s app_metadata is not being updated with a Post-Login Action.

Cause

This was due to using the method api.user.setAppMetadata(key,value) inside a fetch command:

  fetch(path, options)
    .then((response) => {[...]
    }).then((body) => {      if ( <some condition>) {
        api.user.setAppMetadata("key", "value");
        return; }

When calling this method inside the fetch request, it does not work. This Post-Login Action does not have the context to execute that method when in a fetch request.

Solution

Execute the method api.user.setAppMetadata("key", "value") outside of the fetch().then() clause to resolve this issue. For example:

... 
fetch(path, options)
    .then((response) => {[...]
    }).then((body) => {      if ( <some condition>) {
        //execute custom code as needed
        return; }

//outside of the above fetch request this method can now be called as expected
 api.user.setAppMetadata("key", "value");
...