getState()

The getState() method returns a copy of the Adobe Client Data Layer (ACDL) computed state: the result of merging all the data that was pushed so far.

adobeDataLayer.getState(path?: string | string[]): any

This method exists only after ACDL loads. If your code might run before then, call it from a function that you push. See Call methods safely.

Get the entire computed state entire-state

Call getState() without arguments:

window.adobeDataLayer = window.adobeDataLayer || [];
window.adobeDataLayer.push({ page: { title: "Getting started" } });
window.adobeDataLayer.push({ component: { "hero-1": { title: "Learn more", link: "learn-more.html" } } });

window.adobeDataLayer.push(function(dl) {
  console.log(dl.getState());
});

The console shows the following object:

{
  "page": {
    "title": "Getting started"
  },
  "component": {
    "hero-1": {
      "title": "Learn more",
      "link": "learn-more.html"
    }
  }
}

If nothing has been pushed, getState() returns an empty object ({}).

Get a value at a path paths

Pass a path to get one value from the computed state. Separate the keys in the path with dots:

window.adobeDataLayer.push(function(dl) {
  dl.getState("component.hero-1");        // { title: "Learn more", link: "learn-more.html" }
  dl.getState("component.hero-1.title");  // "Learn more"
});

The following rules apply to paths:

  • Array items: Use the item’s index as a key, such as cart.items.0.sku. ACDL 3.x doesn’t support bracket notation, such as cart.items[0].sku.
  • Keys that contain dots: Pass the path as an array of keys instead of a string, such as ["component", "hero.1", "title"].
  • Missing values: If any key in the path doesn’t exist, getState() returns undefined. It doesn’t throw an error.
  • Return type: The value at the path can be of any type, such as an object, an array, a string, a number, or a boolean.

Returned values are copies copies

getState() returns a copy of the computed state, not the computed state itself. Changing the returned object doesn’t change the data layer:

const state = adobeDataLayer.getState();
state.page.title = "Changed";
adobeDataLayer.getState("page.title");  // Still "Getting started"

To change the computed state, push the change with push().

Each call copies the entire computed state, even when you pass a path. On pages with a large data layer, avoid calling getState() in code that runs very often, such as a scroll handler. Read the value once and reuse it.

Read the state in an event listener in-listener

When an event listener runs, the computed state already includes the data from the push that triggered it:

window.adobeDataLayer.push(function(dl) {
  dl.addEventListener("adobeDataLayer:change", function(event) {
    console.log("New page title:", dl.getState("page.title"));
  }, { path: "page.title" });
});
recommendation-more-help
experience-platform-help-collection