# States

## Introduction to **States** in JENTIS

In JENTIS, a **State** defines the **point in time** at which data should be collected from the browser. States are essential for ensuring that data is only extracted when the relevant context is available — whether that’s after the page has loaded, during user interaction, or at key behavioral events.

***

### What is the Goal of a State?

A **state** controls **when** data collection or processing should begin. This allows for event-driven data tracking and ensures that your setup is both **accurate** and **performance-optimized**.

Here are a few common examples of when a state might be triggered:

* **Document Ready**: The DOM is fully loaded
* **User Interaction**: A specific button is clicked
* **Page Transition**: A user navigates to a new page (SPA/virtual pageview)
* **Session Start**: A new session begins

***

### How to Write a State

A **state** in JENTIS is defined as a **JavaScript function** that runs in the user's **web browser**. This function receives a **callback** as an argument, which must be called once the specified condition has occurred.

#### Basic Syntax

```javascript
function(cb) {
    cb(); // Triggers the state immediately
}
```

This is an example of a **state that fires instantly**, without waiting for any condition.

#### Advanced Syntax

For more advanced use cases, the callback can be invoked using the `initState` function with additional configuration options:

```javascript
function(initState) {
  initState({
    stateCallback: function() {
      console.log("State works!");
    },
    requestType: "sendBeacon",
    contextualStateInformation: {
      info: "A",
      value: "123"
    }
  });
}

```

#### Explanation of Parameters

* **`initState()`**:\
  The main callback function provided by JENTIS.\
  You can either call it directly (`initState()`) or pass a configuration object.
* **`stateCallback`**:\
  This function is executed when the **synchronous part of the state logic** is triggered.\
  Use it to run JavaScript logic before or alongside data processing.
* **`requestType`** *(optional)*:\
  Defines the method for sending data to the backend:
  * Default: `XMLHttpRequest`
  * Alternative: `"sendBeacon"` for asynchronous, low-priority transmission.
* **`contextualStateInformation`** *(optional)*:\
  An object containing **additional metadata** that will be attached to the event.\
  These values can be used for enrichment, debugging, or downstream processing. This can be further used on Client-Side Variables ([statecontext](https://docs.jentis.com/developer-guide/variables/client-side-variables/function-arguments/statecontext "mention"))

***

### Example States

#### Document Ready

```javascript
function(cb) {
  if (document.readyState === "complete") {
    cb();
  }
}
```

This state fires when the **JavaScript event `document.readyState === "complete"`** occurs — meaning the DOM is fully loaded and the page is ready.

***

#### Button Click

```javascript
function(cb) {
  document.querySelector('#my-button')?.addEventListener('click', function () {
    cb();
  });
}
```

This state triggers when the **user clicks on a specific button** with the ID `my-button`.

***

#### URL Change (for Single Page Applications)

```javascript
function(cb) {
  let lastUrl = location.href;
  new MutationObserver(() => {
    const currentUrl = location.href;
    if (currentUrl !== lastUrl) {
      lastUrl = currentUrl;
      cb();
    }
  }).observe(document, { subtree: true, childList: true });
}
```

This state detects **URL changes** typical in SPAs, triggering when the user navigates within the app.

***

#### Key Points

* You can access **any browser data** that is available via JavaScript.
* States must be written in **JavaScript ES5** to ensure compatibility with **100% of browsers**.\
  → Use [caniuse.com](https://caniuse.com/) to check browser support for specific features.
* Avoid heavy DOM operations or long delays — states should be lightweight and reliable.
