# Shared Contexts

Source: https://docs.interop.io/browser/capabilities/data-sharing/shared-contexts/index.html

## Overview

A shared context is a named object (holding a `map` of key/value pairs) that stores cross app data. The context object can hold any cross-app data. Any app can update a context or subscribe for context updates and react to them by using the name of the context.

The [Shared Contexts API](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md) offers a simple and effective solution for sharing data between your apps. Imagine you have an app showing a list of clients and an app showing client portfolios. What you need, is your "Portfolio" app to show the portfolio of a specific client that the user has selected from the "Clients" app. You can easily achieve this in a few simple steps by using the Shared Contexts API:

- instruct the "Clients" app to publish updates to a context object holding the `id` of the currently selected client;
- instruct the "Portfolio" app to subscribe for updates of that same context object and specify how the "Portfolio" app should handle the received data in order to update its current state;

The Shared Contexts API is accessible via the [`io.contexts`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md) object.

The [Live Examples](#live_examples) section demonstrates using the Shared Contexts API.

## Setting Contexts

To create a shared context or replace entirely the value of an existing one, use the [`set()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-set) method:

```javascript
const newContext = { backgroundColor: "purple" };

// This will completely overwrite the existing context value.
await io.contexts.set("app-styling", newContext);
```

The [`set()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-set) method overwrites the existing context object, as opposed to the [`update()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-update) method, which only updates the values of its properties.

## Getting Contexts

To get the value of a specific context object, use the [`get()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-get) method:

```javascript
const data = await io.contexts.get("app-styling");
```

## Listing All Contexts

To get the names of all currently available shared contexts, use the [`all()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-all) method:

```javascript
// Returns a string array with the available context names.
const availableContexts = io.contexts.all();
```

## Updating Contexts

To update the value of an existing shared context, use the [`update()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-update) method. New properties will be added, existing ones will be updated, and you can also remove shared context keys by setting them to `null`. If the specified shared context doesn't exist, it will be created:

```javascript
const contextUpdate = {
    backgroundColor: "red",
    alternativeColor: "green"
};

await io.contexts.update("app-styling", contextUpdate);
```

To remove a shared context key, set it to `null`:

```javascript
const keysToRemove = { alternativeColor: null };

await io.contexts.update("app-styling", keysToRemove);
```

## Updating Specific Properties

You can use the [`setPath()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-setPath) and [`setPaths()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-setPaths) methods to update specific shared context properties using a dot-separated string path to point to the location of the property within the shared context object. If the property (or the path) doesn't exist, it will be created. These methods are useful for updating or creating one or more nested properties within the shared context object.

To update or create a single property, use the [`setPath()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-setPath) method. It accepts the name of the shared context, a path to the property to update, and a value for the property:

```javascript
const path = "text.color";
const value = "grey";

await io.contexts.setPath("app-styling", path, value);

// Assuming the context already exists and has this shape:
// { backgroundColor: "red" }, it will be updated as follows:
// { backgroundColor: "red", text: { color: "grey" } }
```

To update or create multiple properties, use the [`setPaths()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-setPaths) method. It accepts the name of the shared context and a list of [`PathValue`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/pathvalue/index.md) objects each containing a path to the property to update and a value for it:

```javascript
const updates = [
    { path: "table.cells", value: { width: 50, height: 30 } },
    { path: "text.color", value: "white" }
];

await io.contexts.setPaths("app-styling", updates);

// Assuming the context already exists and has this shape:
// { backgroundColor: "red", text: { color: "grey" } }, it will be updated as follows:
//
// {
//     backgroundColor: "red",
//     text: {
//         color: "white"
//     },
//     table: {
//         cells: {
//             width: 50,
//             height: 30
//         }
//     }
// }
```

## Subscribing for Context Updates

To subscribe for context updates, use the [`subscribe()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-subscribe) method. It accepts the name of the context as a first required parameter and a function that will handle the context updates as a second required parameter:

```javascript
const handler = (context, delta, removed) => {
    const bgColor = context.backgroundColor;

    console.log(bgColor);
});

await io.contexts.subscribe("app-styling", handler);
```

## Unsubscribing

The [`subscribe()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-subscribe) method returns a `Promise` which resolves with a function you can use to unsubscribe from context updates:

```javascript
const unsubscribe = await io.contexts.subscribe("app-styling", handler);

unsubscribe();
```

## Destroying Contexts

To destroy a context object, use the [`destroy()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-destroy) method:

```javascript
await io.contexts.destroy("app-styling");
```

## Live Examples

### Setting and Getting Context

The following apps demonstrate how to set and get context using the [`get()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-get) and [`set()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-set) methods of the Shared Contexts API.

Create a value in App B (any string) that will be assigned to a pre-defined property of the context object and set the "Browser" context by clicking the "Set Context" button. Click "Get Context" in App A to print the current value of the shared context object.

<div class="d-flex">
    <iframe src="https://k6fn5.csb.app" style="border: none;"></iframe>
</div>

### Subscribing for Context Updates

The following apps demonstrate how to update a shared context object and how to subscribe for updates of a context by using the [`update()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-update) and [`subscribe()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-subscribe) methods of the Shared Contexts API.

Click the "Subscribe" button in App A to subscribe for updates of the "Browser" context. Every time the "Browser" context changes, the context value will be printed. Create a context value and click the "Update Context" button in App B to update the "Browser" context.

<div class="d-flex">
    <iframe src="https://8df8e.csb.app" style="border: none;"></iframe>
</div>

### Discovering Contexts

The following apps demonstrate how to get a list of all contexts and find a specific context by name.

Create several contexts with different names from App B. Input the name of the context you want to find in App A and click the "Find Context" button to print the context.

<div class="d-flex mb-3">
    <iframe src="https://wpdr7.csb.app" style="border: none;"></iframe>
</div>

## API Reference

For a complete list of the available Shared Contexts API methods and properties, see the [Shared Contexts API Reference Documentation](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md).
