# React Tutorial

Source: https://docs.interop.io/browser/tutorials/react/index.html

## Overview

This tutorial is designed to walk you through every aspect of **io.Connect Browser** - setting up a project, initializing a [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md), multiple [Browser Client](https://docs.interop.io/browser/developers/browser-client/overview/index.md) apps, and extending your apps with [Shared Contexts](https://docs.interop.io/browser/capabilities/data-sharing/shared-contexts/index.md), [Interop](https://docs.interop.io/browser/capabilities/data-sharing/interop/index.md), [Window Management](https://docs.interop.io/browser/capabilities/windows/window-management/index.md), [Channels](https://docs.interop.io/browser/capabilities/data-sharing/channels/index.md), [App Management](https://docs.interop.io/browser/capabilities/app-management/index.md), [Workspaces](https://docs.interop.io/browser/capabilities/windows/workspaces/overview/index.md), and more io.Connect [capabilities](https://docs.interop.io/browser/capabilities/app-management/index.md).

This guide uses React and its goal is to allow you to put to practice the basic concepts of **io.Connect Browser** in a React app by using the [`@interopio/react-hooks`](https://www.npmjs.com/package/@interopio/react-hooks) library. It's strongly recommended to go through the [JavaScript](https://docs.interop.io/browser/tutorials/javascript/index.md) tutorial first in order to get a better understanding of **io.Connect Browser** without the added complexity of a web framework.

## Introduction

You are a part of the IT department of a big multi-national bank and you have been tasked to lead the creation of a project which will be used by the Asset Management department of the bank. The project will consist of three apps bootstrapped with [Vite](https://vite.dev/):

- **Clients** - displays a full list of clients and details about them;
- **Stocks** - displays a full list of stocks with prices. When the user clicks on a stock, details about the selected stock should be displayed;
- **Stock Details** - displays details for a selected stock after the user clicks on a stock in the **Stocks** app;

All apps are being developed by different teams within the organizations and therefore are being hosted at different origins.

As an end result, the users want to be able to run the apps as Progressive Web Apps in separate windows in order to take advantage of their multi-monitor setups. Also, they want the apps, even though in separate windows, to be able to communicate with each other. For example, when a client is selected in the **Clients** app, the **Stocks** app should display only the stocks of the selected client.

## Prerequisites

You must have a valid license key for **io.Connect Browser**.

This tutorial assumes that you are familiar with [React](https://reactjs.org), Vite, and the concepts of JavaScript and asynchronous programming.

It's also recommended to have the [Browser Platform](https://docs.interop.io/browser/developers/browser-platform/overview/index.md), [Browser Client](https://docs.interop.io/browser/developers/browser-client/overview/index.md) and **io.Connect Browser** [API Reference](https://docs.interop.io/browser/reference/javascript/io.connect%20browser/index.md) documentation available.

Each main chapter demonstrates a different io.Connect capability whose documentation you can find in the [Capabilities](https://docs.interop.io/browser/capabilities/home-app/overview/index.md) section of the documentation.

## Tutorial Structure

The tutorial code is located in the [browser-tutorials](https://github.com/InteropIO/browser-tutorials) GitHub repo with the following structure:

```cmd
/angular
    /solution
    /start
/javascript
    /solution
    /start
/react
    /solution
    /start
/rest-server
```

| Directory | Description |
|-----------|-------------|
| `/javascript`, `/react`, `/angular` | Contain the starting files for the tutorials and also a full solution for each of them. |
| `/rest-server` | A simple server used in the tutorials to serve the necessary JSON data. |

## 1. Initial Setup

Clone the [browser-tutorials](https://github.com/InteropIO/browser-tutorials) GitHub repo to get the tutorial files.

### 1.1. Start Files

Next, go to the `/react/start` directory which contains the starting files for the project. The tutorial examples assume that you will be working in the `/start` directory, but you can also move the files and work from another directory.

The `/start` directory contains the following:

| Directory | Description |
|-----------|-------------|
| `/clients` | This is the **Clients** app bootstrapped with Vite. This will be the [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md) of your **io.Connect Browser** project. |
| `/portfolio-downloader` | This is the **Portfolio Downloader** app  bootstrapped with Vite, which will be used in the [Intents](#10_intents) chapter.  |
| `/stock-details` | This is the **Stock Details** app  bootstrapped with Vite. |
| `/stocks` | This is the **Stocks**  bootstrapped with Vite. |
| `/workspace` | This is a **Workspaces App**, which will be used in the [Workspaces](#9_workspaces) chapter. |

The **Clients**, **Stocks**, **Stock Details**, and **Portfolio Downloader** apps contain the following resources:

| Directory | Description |
|-----------|-------------|
| `/public` | Contains all static assets for each app such as icons and other files that will be available in the final build. |
| `/src` | Contains the main entry point for each app - the `main.jsx` file, all React components for each app, an `io.js` file (methods for interaction with the io.Connect framework), and CSS files. |
| `.env.example` | This file is present only in the **Clients** app. It should be renamed to `.env` and you should use it to specify a license key for the Main app of **io.Connect Browser**. |

The **Clients** app also contains a `/plugins` directory with [Plugins](https://docs.interop.io/browser/capabilities/plugins/index.md) that will be used in the [Plugins](#8_plugins) chapter.

Go to the `/react/start` directory, open a command prompt, and run the following commands to install the necessary dependencies and launch all apps:

```cmd
npm install
npm run install:apps
npm start
```

This will install all root and app dependencies and launch the apps on different ports:

| URL | App |
|-----|-----|
| `http://localhost:3000/` | **Clients** |
| `http://localhost:3001/` | **Stocks** |
| `http://localhost:3002/` | **Stock Details** |
| `http://localhost:9300/` | **Workspaces App** |
| `http://localhost:9400/` | **Portfolio Downloader** |

### 1.2. Solution Files

Before you continue, take a look at the solution files. You are free to use the solution as you like - you can check after each section to see how it solves the problem, or you can use it as a reference point in case you get stuck.

Go to the `/rest-server` directory and start the REST Server (as described in the [REST Server](#1_initial_setup-13_rest_server) chapter).

Go to the `/react/solution/clients` directory, rename the `.env.example` file to `.env` and provide a valid license key for **io.Connect Browser** by using the `VITE_LICENSE_KEY` environment variable.

Go to the `/react/solution` directory, open a command prompt, and run the following commands to install the necessary dependencies and start all apps:

```cmd
npm install
npm run install:apps
npm start
```

You can now access the entry point of the project (the **Clients** app) at `http://localhost:3000/clients`.

### 1.3. REST Server

Before starting with the project, go to the `/rest-server` directory and start the REST server that will host the necessary data for the apps:

```cmd
npm install
npm start
```

This will launch the server at port 8080.

### 1.4. React Project Setup

This tutorial starts with three initial apps. As the user requirements change, however, your **io.Connect Browser** project will expand with more apps. Here you will learn how to create a new React app and set it up correctly in order to enable it to work with **io.Connect Browser**. When you have to create and set up new apps later on in the tutorial, you can refer back to this chapter and follow the steps to ensure that your app has been configured properly:

1. Go to the directory where you want your new app to be created, open a command prompt and run the following command replacing `my-app` with the name of your app:

```cmd
npm create vite@latest my-app
```

2. Install the following dependencies in the root directory of your app:

```cmd
npm install @interopio/react-hooks bootstrap@4.4.1
```

3. Configure a port for your app by using the `port` property of the `server` object in the `vite.config.js` file in the root directory of your app:

```javascript
import react from "@vitejs/plugin-react";

export default {
    base: "./",
    plugins: [react()],
    server: {
        port: 3003
    }
};
```

> ⚠️ *Note that the `port` value must be different for each app in the project. The initial apps already occupy ports 3000, 3001, 3002, 9300, and 9400.*

4. Start your app by running the following command from its root directory:

```cmd
npm start
```

5. Create or edit the code for the new app by following the specific instructions in the respective chapters.

## 2. Project Setup

### 2.1. Main App

Each **io.Connect Browser** project must have a single central app called [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md), or Browser Platform app. In a real-life scenario, this would be an app used for discovering and listing available apps, Workspaces, handling notifications, and much more. However, your goal now is to learn about all these aspects with as little complexity as possible. That's why the **Clients** app will serve as your Main app. The users will open the **Clients** app and from there they will be able to click on a client and see their stocks and so on.

Setting up a Main app is as simple as calling a function. First, install the [`@interopio/react-hooks`](https://www.npmjs.com/package/@interopio/react-hooks) and the [`@interopio/browser-platform`](https://www.npmjs.com/package/@interopio/browser-platform) libraries in the **Clients** app and initialize them. The [`@interopio/browser-platform`](https://www.npmjs.com/package/@interopio/browser-platform) library handles the entire io.Connect environment, which is necessary for the [Browser Client](https://docs.interop.io/browser/developers/browser-client/overview/index.md) apps to be able to connect to the Main app and to each other.

Go to the **Clients** app and install the `@interopio/react-hooks` library:

```cmd
npm install @interopio/react-hooks
```

Next, install the [`@interopio/browser-platform`](https://www.npmjs.com/package/@interopio/browser-platform) library:

```cmd
npm install @interopio/browser-platform
```

Go to the `main.jsx` file of the **Clients** app, import the `IOBrowserPlatform()` factory function, and provide a valid license key for **io.Connect Browser**:

```javascript
import ReactDOM from "react-dom/client";
import { IOConnectProvider } from "@interopio/react-hooks";
import IOBrowserPlatform from "@interopio/browser-platform";

const config = {
    // Provide your license key for io.Connect Browser.
    licenseKey: import.meta.env.VITE_LICENSE_KEY
};

const settings = {
    browserPlatform: {
        factory: IOBrowserPlatform,
        config
    }
};

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <IOConnectProvider settings={settings}>
        <Clients />
    </IOConnectProvider>
);
```

To use the io.Connect APIs in the `<Clients />` component, import the `IOConnectContext` object and the `useIOConnect()` hook from the `@interopio/react-hooks` library. Pass the `IOConnectContext` to the `useContext()` React hook and use the returned object to access the io.Connect APIs:

```javascript
import { useContext } from "react";
import { IOConnectContext, useIOConnect } from "@interopio/react-hooks";

function Clients() {
    const io = useContext(IOConnectContext);
};
```

To allow the component to show whether io.Connect is available, uncomment the commented out `<div>` element in the `return` statement:

```javascript
return (
    <div className="container-fluid">
        <div className="row">
            <div className="col-md-2">
                {!io && (
                <span id="ioSpan" className="badge badge-warning">
                    io.Connect is unavailable
                </span>
                )}
                {io && (
                <span id="ioSpan" className="badge badge-success">
                    io.Connect is available
                </span>
                )}
            </div>
            ...
        </div>
        ...
    </div>
);
```

You will see a small green label at the top left corner of the **Clients** app with the text "io.Connect is available".

The **Clients** app is now setup as the [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md) of your **io.Connect Browser** project.

Next, initialize the rest of the apps to connect them to the io.Connect environment as [Browser Clients](https://docs.interop.io/browser/developers/browser-client/overview/index.md).

### 2.2. Browser Clients

Now that you have a fully functional [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md), you must [initialize](https://docs.interop.io/browser/developers/browser-client/react/index.md) the [`@interopio/browser`](https://www.npmjs.com/package/@interopio/browser) library in the rest of the apps. This will allow them to connect to the **Clients** app and communicate with each other.

Go to the **Stocks** and **Stock Details** apps and install the [`@interopio/react-hooks`](https://www.npmjs.com/package/@interopio/react-hooks) library:

```cmd
npm install @interopio/react-hooks
```

Go to the `main.jsx` files of the **Stocks** and **Stock Details** apps and add the following to make the [`@interopio/browser`](https://www.npmjs.com/package/@interopio/browser) library available in the `<Stocks />` and `<StockDetails />` components respectively:

```javascript
// In `main.jsx` of the Stocks app.
import ReactDOM from "react-dom/client";
import IOBrowser from "@interopio/browser";
import { IOConnectProvider } from "@interopio/react-hooks";

const settings = {
    browser: {
        factory: IOBrowser
    }
};

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    // Replace `<Stocks />` with the `<StockDetails />` component for the Stock Details app.
    <IOConnectProvider settings={settings}>
        <Stocks />
    </IOConnectProvider>
);
```

To use the io.Connect APIs in the `<Stocks />` and `<StockDetails />` components, import the `IOConnectContext` object and the `useIOConnect()` hook from the io.Connect React Hooks library. Pass the `IOConnectContext` to the `useContext()` React hook and use the returned object to access the io.Connect APIs:

```javascript
// In `Stocks.jsx` of the Stocks app.
import { useContext } from "react";
import { IOConnectContext, useIOConnect } from "@interopio/react-hooks";

function Stocks() {
    const io = useContext(IOConnectContext);
};
```

To allow the components to show whether io.Connect is available, uncomment the commented out `<div>` element in their `return` statements:

```javascript
return (
    <div className="container-fluid">
        <div className="row">
            <div className="col-md-2">
                {!io && (
                <span id="ioSpan" className="badge badge-warning">
                    io.Connect is unavailable
                </span>
                )}
                {io && (
                <span id="ioSpan" className="badge badge-success">
                    io.Connect is available
                </span>
                )}
            </div>
            ...
        </div>
        ...
    </div>
);
```

> ⚠️ *Note that when you refresh the Browser Client apps, you will see that the io.Connect initialization is unsuccessful. This is because the Browser Client apps can't currently connect to the io.Connect environment provided by the [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md) and therefore can't discover the Main app or each other. To be able to initialize the [`@interopio/browser`](https://www.npmjs.com/package/@interopio/browser) library, all [Browser Client](https://docs.interop.io/browser/developers/browser-client/overview/index.md) apps must be started by the Main app or by another Browser Client app already connected to the io.Connect environment. Currently, the only way to open these apps is via the URL in the address bar of the browser. The next chapter will teach you how to open the **Stocks** app from the **Clients** app which will solve this problem.*

To verify that the initializations are correct, open the browser console of the **Clients** app (press `F12`) and execute the following:

```javascript
await io.windows.open("stocks", "http://localhost:3001/").catch(console.error);
```

This will instruct the **Clients** app to open the **Stocks** app by using the [Window Management API](https://docs.interop.io/browser/capabilities/windows/window-management/index.md). The **Stocks** app will now be able to connect to the io.Connect environment and initialize the `@interopio/browser` library correctly. Repeat this for the rest of the apps by changing the values of the `name` and the `url` parameters when calling the [`open()`](https://docs.interop.io/browser/capabilities/windows/window-management/index.md#API-open) method.

## 3. Window Management

The goal of this chapter is to start building the user flow of the entire project. The end users will open the **Clients** app and will be able to open the **Stocks** app from the "Stocks" button in it. Clicking on a stock in the **Stocks** app will open the **Stock Details** app.

Currently, the only way for the user to open the **Stocks** app is to manually enter its URL in the address bar. This, however, prevents the app from connecting to the io.Connect environment. Also, the users want the **Stock Details** app to open in a new window with specific dimensions and position. To achieve all this, you will use the [Window Management API](https://docs.interop.io/browser/reference/javascript/windows/api/index.md).

> ℹ️ *See also the [Capabilities > Windows > Window Management](https://docs.interop.io/browser/capabilities/windows/window-management/index.md) documentation.*

### 3.1. Opening Windows Dynamically

Instruct the **Clients** app to open the **Stocks** app in a new window when the user clicks on the "Stocks" button. Go to the `io.js` file of the **Clients** app and define a function that will open the **Stocks** app in a new window. Use the [`open()`](https://docs.interop.io/browser/reference/javascript/windows/api/index.md#API-open) method to open the **Stocks** app in a new window. The `windowID` variable ensures that the name of each new **Stocks** instance will be unique:

```javascript
let windowID = 0;

export const openStocks = (io) => () => {
    // The `name` and `url` parameters are required. The window name must be unique.
    const name = `Stocks-${++windowID}`;
    const URL = "http://localhost:3001/";

    io.windows.open(name, URL).catch(console.error);
};
```

Import this function in the `<Clients />` component, pass it to the `useIOConnect()` hook, and set it as the `onClick` handler of the "Stocks" button in the `return` statement:

```javascript
import { openStocks } from "./io";

function Clients() {
    ...
    const onClickStocks = useIOConnect(openStocks);
    ...
    return (
        <div className="container-fluid">
            <div className="row">
                ...
                <div className="col-md-8">
                    <h1 className="text-center">Clients</h1>
                </div>
                <div className="col-md-2 py-2">
                    <button className="btn btn-primary" onClick={onClickStocks}>Stocks</button>
                </div>
            </div>
            ...
        </div>
    );
};
```

Clicking on the "Stocks" button will now open the **Stocks** app.

> ⚠️ *Note that you must allow popups in the browser and remove any popup blockers to allow the **Stocks** window to open.*

To complete the user flow, instruct the **Stocks** app to open a new window each time the user clicks on a stock. Remember that each io.Connect Window must have a unique name. To avoid errors resulting from attempting to open io.Connect Windows with conflicting names, check whether the clicked stock has already been opened in a new window.

Go to the `io.js` file of the **Stocks** app and define a callback that will open the **Stock Details** app in a new window. Use the [`list()`](https://docs.interop.io/browser/reference/javascript/windows/api/index.md#API-list) method to get a collection of all io.Connect Windows and check whether the clicked stock is already open in a window. It's safe to search by window name, because all io.Connect Window instances must have a unique `name` property:

```javascript
export const openStockDetails = (io) => (stock) => {
    const name = `StockDetails-${stock.RIC}`;
    const URL = "http://localhost:3002/";

    // Check whether the clicked stock has already been opened in a new window.
    const stockWindowExists = io.windows.list().find(w => w.name === name);

    if (!stockWindowExists) {
        io.windows.open(name, URL).catch(console.error);
    };
};
```

Import this callback in the `<Stocks />` component, pass it to the `useIOConnect()` hook and set it as the `onClick` handler of each table row element in the `return` statement:

```javascript
import { openStockDetails } from "./io";

function Stocks() {
    ...
    const showStockDetails = useIOConnect(openStockDetails);
    ...
    return (
        ...
        {portfolio.map(({ RIC, Description, Bid, Ask, ...rest }) => (
            <tr
                key={RIC}
                onClick={() => showStockDetails({ RIC, Description, Bid, Ask, ...rest })}
            >
                <td>{RIC}</td>
                <td>{Description}</td>
                <td className="text-right">{Bid}</td>
                <td className="text-right">{Ask}</td>
            </tr>
        ))}
        ...
    );
};
```

> ⚠️ *Note that you must allow popups in the browser and remove any popup blockers to allow the **Stock Details** window to open.*

### 3.2. Window Settings

To position the new **Stock Details** window, extend the logic in the [`open()`](https://docs.interop.io/browser/reference/javascript/windows/api/index.md#API-open) method by passing an optional [`Settings`](https://docs.interop.io/browser/reference/javascript/windows/settings/index.md) object containing specific values for the window size (`width` and `height`) and position (`top` and `left`):

```javascript
export const openStockDetails = (io) => (stock) => {
    const name = `StockDetails-${stock.RIC}`;
    const URL = "http://localhost:3002/";
    // Optional configuration object for the newly opened window.
    const config = {
        left: 100,
        top: 100,
        width: 550,
        height: 550
    };

    const stockWindowExists = io.windows.list().find(w => w.name === name);

    if (!stockWindowExists) {
        io.windows.open(name, URL, config).catch(console.error);
    };
};
```

### 3.3. Window Context

To allow the **Stock Details** app to display information about the selected stock, set the stock selected in the **Stocks** app as a context to the newly opened **Stock Details** window. The **Stock Details** window will then access its context and extract the necessary stock information.

Add a `context` property to the window configuration object and assign the `stock` object as its value:

```javascript
export const openStockDetails = (io) => (stock) => {
    const name = `StockDetails-${stock.RIC}`;
    const URL = "http://localhost:3002/";
    const config = {
        left: 100,
        top: 100,
        width: 550,
        height: 550,
        // Set the `stock` object as a context for the new window.
        context: { stock }
    };

    const stockWindowExists = io.windows.list().find(w => w.name === name);

    if (!stockWindowExists) {
        io.windows.open(name, URL, config).catch(console.error);
    };
};
```

Next, go to the `io.js` file of the **Stock Details** app and define a function that will get the window context. Get a reference to the current window by using the [`my()`](https://docs.interop.io/browser/reference/javascript/windows/api/index.md#API-my) method and retrieve its context with the [`getContext()`](https://docs.interop.io/browser/reference/javascript/windows/webwindow/index.md#WebWindow-getContext) method of the [`WebWindow`](https://docs.interop.io/browser/reference/javascript/windows/webwindow/index.md) object:

```javascript
export const getMyWindowContext = (setWindowContext) => async (io) => {
    const myWindow = io.windows.my();
    const context = await myWindow.getContext();

    setWindowContext(context);
};
```

Go to the `<StockDetails />` component, define a state variable that will hold the window context and pass the `getMyWindowContext()` function to the `useIOConnect()` hook:

```javascript
import { useState } from "react";
import { getMyWindowContext } from "./io";

function StockDetails() {
    const [windowContext, setWindowContext] = useState({});

    // Get the window context.
    useIOConnect(getMyWindowContext(setWindowContext));

    // Extract the selected stock from the window context.
    const {
        stock: { RIC, BPOD, Bloomberg, Description, Exchange, Venues, Bid, Ask } = {}
    } = windowContext || {};
};
```

Now, when you click on a stock in the **Stocks** app, the **Stock Details** app will open in a new window displaying information about the selected stock.

## 4. Interop

Now, you will use the [Interop API](https://docs.interop.io/browser/reference/javascript/interop/api/index.md) to pass the portfolio of the selected client to the **Stocks** app and show only the stocks present in their portfolio.

> ℹ️ *See also the [Capabilities > Data Sharing > Interop](https://docs.interop.io/browser/capabilities/data-sharing/interop/index.md) documentation.*

### 4.1. Registering Interop Methods and Creating Streams

When a user clicks on a client, the **Stocks** app should show only the stocks owned by this client. You can achieve this by registering an Interop method in the **Stocks** app which, when invoked, will receive the portfolio of the selected client and re-render the stocks table. Also, the **Stocks** app will create an Interop stream to which it will push the new stock prices. Subscribers to the stream will get notified when new prices have been generated.

Go to the `io.js` file of the **Stocks** app and define a callback for registering an Interop method. Use the [`register()`](https://docs.interop.io/browser/reference/javascript/interop/api/index.md#API-register) method to register an Interop method and pass a method name and a callback for handling method invocations:

```javascript
import { SET_CLIENT_METHOD } from "./constants";

export const registerSetClientMethod = (setClient) => (io) => {
    // Register an Interop method by providing a name and a handler.
    io.interop.register(SET_CLIENT_METHOD, setClient);
};
```

Import the callback in the `<Stocks />` component, define a state variable that will hold the selected client, and pass the callback to the `useIOConnect()` hook:

```javascript
import { registerSetClientMethod } from "./io";

function Stocks() {
    ...
    const [{ clientId, clientName }, setClient] = useState({});
    useIOConnect(registerSetClientMethod(setClient));
    ...
};
```

Modify the `fetchPortfolio()` function in the existing `useEffect()` hook to fetch the selected client portfolio. Pass `clientId` as a `useEffect()` dependency, so that `fetchPortfolio()` will be called whenever a new client is selected and the component is re-rendered:

```javascript
useEffect(() => {
    const fetchPortfolio = async () => {
        try {
            const url = `http://localhost:8080${clientId ? `/api/portfolio/${clientId}` : "/api/portfolio"}`;
            const response = await fetch(url, REQUEST_OPTIONS);
            const portfolio = await response.json();
            setPortfolio(portfolio);
        } catch (error) {
            console.error(error);
        };
    };
    fetchPortfolio();
}, [clientId]);
```

Finally, add an element to show the client name and ID above the stocks table in the `return` statement of the `<Stocks />` component.

```javascript
return (
    ...
        {clientId && (
            <h2 className="p-3">
                Client {clientName} - {clientId}
            </h2>
        )}
    ...
);
```

Streams can be described as special Interop methods. Go to the `io.js` file of the **Stocks** app and define a callback for creating an Interop stream. Use the [`createStream()`](https://docs.interop.io/browser/reference/javascript/interop/api/index.md#API-createStream) method to create an Interop stream. Pass a name for the stream to `createStream()`. Call the predefined `publishInstrumentPrice()` callback and pass the created stream to it:

```javascript
import { SET_PRICES_STREAM } from "./constants";

export const createInstrumentStream = async (io) => {
    const stream = await io.interop.createStream(SET_PRICES_STREAM);
    publishInstrumentPrice(stream);
};
```

Push the generated prices to the stream in the `publishInstrumentPrice()` callback:

```javascript
export const publishInstrumentPrice = (stream) => {
    setInterval(() => {
        const stocks = {
            ...
        };

        // Push the stock prices to the stream.
        stream.push(stocks);
    }, 1500);
};
```

Import the `createInstrumentStream()` callback in the `<Stocks />` component and pass it to the `useIOConnect()` hook:

```javascript
import { createInstrumentStream } from "./io";

function Stocks() {
    ...
    useIOConnect(createInstrumentStream);
    ...
};
```

Next, you will find and invoke the registered method from the **Clients** app.

### 4.2. Method Discovery

Go to the `io.js` file of the **Clients** app and define a callback for discovering and invoking the Interop method. Use the [`methods()`](https://docs.interop.io/browser/reference/javascript/interop/api/index.md#API-methods) method to check for a registered Interop method with the specified name:

```javascript
import { SET_CLIENT_METHOD } from "./constants";

export const setClientPortfolioInterop = (io) => ({ clientId, clientName }) => {
    // Check whether the method exists.
    const isMethodRegistered = io.interop
        .methods()
        .some(({ name }) => name === SET_CLIENT_METHOD.name);
};
```

### 4.3. Method Invocation

Next, invoke the Interop method if it has been registered.

Use the [`invoke()`](https://docs.interop.io/browser/reference/javascript/interop/api/index.md#API-invoke) method and pass the name of the Interop method as a first argument and an object containing the client ID and the client name as a second:

```javascript
import { SET_CLIENT_METHOD } from "./constants";

export const setClientPortfolioInterop = (io) => ({ clientId, clientName }) => {
    // Check whether the method exists.
    const isMethodRegistered = io.interop
        .methods()
        .some(({ name }) => name === SET_CLIENT_METHOD.name);
    if (isMethodRegistered) {
        // Invoke an Interop method by name and provide arguments for the invocation.
        io.interop.invoke(SET_CLIENT_METHOD.name, { clientId, clientName });
    };
};
```

Import the callback in the `<Clients />` component and pass it to the `useIOConnect()` hook to define a handler function for the `onClick` property of each table row in the **Clients** app:

```javascript
import { setClientPortfolioInterop } from "./io";

function Clients() {
    ...
    const onClickClients = useIOConnect(setClientPortfolioInterop);
    ...
};
```

In the `return` statement, attach the `onClick` handler to each client row:

```javascript
return (
    ...
        <tbody>
            {clients.map(({ name, pId, gId, accountManager, portfolio, ...rest }) => (
                <tr
                    key={pId}
                    onClick={() => {
                        onClickClients({ clientId: gId, clientName: name });
                    }}
                >
                    <td>{name}</td>
                    <td>{pId}</td>
                    <td>{gId}</td>
                    <td>{accountManager}</td>
                </tr>
            ))}
        </tbody>
    ...
);
```

Now, when you click on a client in the **Clients** app, the **Stocks** app will display only the stocks that are in the portfolio of the selected client.

### 4.4. Stream Subscription

Go to the `io.js` files of the **Stocks** and **Stock Details** apps and define a callback for creating a stream subscription. This callback will receive as parameters a handler function responsible for updating the stock prices in the respective component, and either an array of stocks or a single stock depending on whether the callback has been invoked by the **Stocks** or the **Stock Details** app:

```javascript
import { SET_PRICES_STREAM } from "./constants";

export const subscribeForInstrumentStream = (handler) => async (io, stock) => {
    if (stock) {
        // Create a stream subscription.
        const subscription = await io.interop.subscribe(SET_PRICES_STREAM);
        const handleUpdates = ({ data: stocks }) => {
            if (stocks[stock]) {
                handler(stocks[stock]);
            } else if (Array.isArray(stock)) {
                handler(stocks);
            };
        };
        // Specify a handler for new data.
        subscription.onData(handleUpdates);
        // Specify a handler if the subscription fails.
        subscription.onFailed(console.log);

        return subscription;
    };
};
```

Go to the `<Stocks />` component and create a stream subscription. The stream used in the tutorial publishes all possible stock prices and it isn't necessary to close and renew the subscription when a new client has been selected. However, to simulate a real project scenario, pass the `portfolio` as a dependency of the `useIOConnect()` hook to trigger a new subscription every time the `portfolio` has been updated:

```javascript
import { subscribeForInstrumentStream } from "./io";

function Stocks() {
    ...
    // The prices will be updated when new data is received from the stream.
    const [prices, setPrices] = useState({});
    // Create a stream subscription that will be renewed every time the `portfolio` changes.
    const subscription = useIOConnect(
        (io, portfolio) => {
            if (portfolio.length > 0) {
                return subscribeForInstrumentStream(setPrices)(io, portfolio);
            }
        },
        [portfolio]
    );

    useEffect(() => {
        const fetchPortfolio = async () => {
            try {
                // Close the existing subscription when a new client has been selected.
                subscription &&
                typeof subscription.close === "function" &&
                subscription.close();

                const url = `http://localhost:8080/api/portfolio/${clientId ? clientId : ""}`;
                const response = await fetch(url, REQUEST_OPTIONS);
                const portfolio = await response.json();
                setPortfolio(portfolio);
            } catch (error) {
                console.error(error);
            };
        };
        fetchPortfolio();
    }, [clientId]);
    ...
};
```

Update the code for displaying the `Ask` and `Bid` prices by taking their values from the `prices` variable that is updated when new data is received from the stream:

```javascript
return (
    ...
        <tbody>
            {portfolio.map(({ RIC, Description, Bid, Ask, ...rest }) => (
                <tr
                    onClick={() => showStockDetails({ RIC, Description, Bid, Ask, ...rest })}
                    key={RIC}
                >
                    <td>{RIC}</td>
                    <td>{Description}</td>
                    <td className="text-right">
                        {prices[RIC] ? prices[RIC].Bid : Bid}
                    </td>
                    <td className="text-right">
                        {prices[RIC] ? prices[RIC].Ask : Ask}
                    </td>
                </tr>
            ))}
        </tbody>
    ...
);
```

Finally, go to the `<StockDetails />` component, extract the `Bid` and the `Ask` from the state, and create a stream subscription by passing the `setPrices` method as a handler for the new stream data and the `RIC` to target the stock for which to get the prices.

```javascript
import { subscribeForInstrumentStream } from "./io";

function StockDetails() {
    ...
    const {
        stock: { RIC, BPOD, Bloomberg, Description, Exchange, Venues } = {}
    } = windowContext || {};

    const [{ Bid, Ask }, setPrices] = useState({ Bid: windowContext.Bid, Ask: windowContext.Ask});

    useIOConnect(subscribeForInstrumentStream(setPrices), [RIC]);
    ...
};
```

> ⚠️ *Note that each new instance of the **Stocks** app will create a new stream instance. In real-life scenarios, this should be handled differently - e.g., by a system app acting as a designated data provider. For more details, see [Plugins](https://docs.interop.io/browser/capabilities/plugins/index.md).*

## 5. Shared Contexts

The next request of the users is to be able to see in the **Stock Details** app whether the selected client has the selected stock in their portfolio. This time you will use the [Shared Contexts API](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md) to connect the **Clients**, **Stocks**, and **Stock Details** apps by using shared context objects.

> ℹ️ *See also the [Capabilities > Data Sharing > Shared Contexts](https://docs.interop.io/browser/capabilities/data-sharing/shared-contexts/index.md) documentation.*

### 5.1. Updating a Context

Go to the `io.js` file of the **Clients** and **Stocks** apps and define a function for updating the shared context object. Use the [`update()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-update) method to create and set a shared context object by providing a name and value - it will hold the selected client object. Other apps will be able to subscribe for updates to this context and be notified when its value changes:

```javascript
import { SHARED_CONTEXT_NAME } from "./constants";

export const setClientPortfolioSharedContext = (io) => (
    {
        clientId = "",
        clientName = "",
        portfolio = ""
    }
) => {
    io.contexts.update(SHARED_CONTEXT_NAME, {
        clientId,
        clientName,
        portfolio
    });
};
```

Go to the **Clients** app and replace the `setClientPortfolioInterop()` handler for selecting a client with the `setClientPortfolioSharedContext()` one. Pass the `portfolio` object to `onClickSharedContext()` when calling it:

```javascript
import { setClientPortfolioSharedContext } from "./io";

function Clients() {
    ...
    // const onClickClients = useIOConnect(setClientPortfolioInterop);
    const onClickSharedContext = useIOConnect(setClientPortfolioSharedContext);
    ...

    return (
        ...
            {clients.map(({ name, pId, gId, accountManager, portfolio, ...rest }) => (
                <tr
                    key={pId}
                    onClick={() => {
                        onClickSharedContext({ clientId: gId, clientName: name, portfolio })
                    }}
                >
                ...
            ))}
        ...
    );
};
```

Go to the **Stocks** app and define a handler for updating the shared context with the `useIOConnect()` hook. Also, add a "Show All" button in the `return` statement of the component that will invoke the handler on button click. When the user clicks on the "Show All" button, the **Stocks** will clear the data in the shared context in order to display information about all available stocks:

```javascript
import { setClientPortfolioSharedContext } from "./io";

function Stocks() {
    ...
    const updateClientContext = useIOConnect(setClientPortfolioSharedContext);
    ...
    return (
        <div className="container-fluid">
            <div className="row">
                ...
                <div className="col-md-8">
                    <h1 className="text-center">Stocks</h1>
                </div>
                <div className="col-md-2 py-2">
                    <button
                        type="button"
                        className="mb-3 btn btn-primary"
                        onClick={() => updateClientContext({})}
                    >
                        Show All
                    </button>
                </div>
            </div>
            ...
        </div>
    );
};
```

### 5.2. Subscribing for Context Updates

Subscribe the **Stocks** and **Stock Details** apps for updates to the same context object in order to update them accordingly when the user selects a new client.

Go to the `io.js` files of the **Stocks** and **Stock Details** apps and define a function for subscribing to the context. Use the [`subscribe()`](https://docs.interop.io/browser/reference/javascript/shared%20contexts/api/index.md#API-subscribe) method and pass the shared context name and a handler for the context updates as arguments:

```javascript
import { SHARED_CONTEXT_NAME } from "./constants";

export const subscribeForSharedContext = (handler) => (io) => {
    // Subscribing for the shared context.
    io.contexts.subscribe(SHARED_CONTEXT_NAME, handler);
};
```

Go to the `<Stocks />` component and replace the `registerSetClientMethod()` handler with the `subscribeForSharedContext()` one:

```javascript
import { subscribeForSharedContext } from "./io";

function Stocks() {
    ...
    useIOConnect(subscribeForSharedContext(setClient));
    ...
};
```

Go to the `<StockDetails />` component and subscribe for updates to the shared context. Add an element in the `return` statement that will be displayed conditionally depending on whether the client has the selected stock in their portfolio. Add the client information (`clientId`, `clientName`, `portfolio`) to the component state to be able to display data about the currently selected client and use the `portfolio` to determine whether the client has the selected stock in their portfolio:

```javascript
import { subscribeForSharedContext } from "./io";

function StockDetails() {
    ...
    const [{ clientId, clientName, portfolio }, setClient] = useState({});
    ...
    useIOConnect(subscribeForSharedContext(setClient));

    return (
        <div className="container-fluid">
            <div className="row">
                ...
                {clientId && (
                    <>
                        <h2 className="p-3">
                            Client {clientName} - {clientId}
                        </h2>
                        {RIC && portfolio.length && !portfolio.includes(RIC) && (
                            <h4 className="p-3">
                                The client doesn't have this stock in their portfolio.
                            </h4>
                        )}
                    </>
                )}
            </div>
            ...
        </div>
    );
};
```

Now, the **Stock Details** app will show whether the client selected from the **Clients** app has the the displayed stock in their portfolio.

## 6. Channels

The latest requirement from the users is to be able to work with multiple clients at a time by having multiple instances of the **Stocks** app show the portfolios of different clients. Currently, no matter how many instances of the **Stocks** app are running, they are all listening for updates to the same context and therefore all show information about the same selected client. Here you will use the [Channels API](https://docs.interop.io/browser/reference/javascript/channels/api/index.md) to allow each instance of the **Stocks** app to subscribe for updates to the context of a different Channel. The different Channels are color-coded and the user will be able to select a Channel from a Channel Selector UI. The **Clients** app will update the context of the currently selected Channel when the user clicks on a client.

> ℹ️ *See also the [Capabilities > Data Sharing > Channels](https://docs.interop.io/browser/capabilities/data-sharing/channels/index.md) documentation.*

### 6.1. Channels Configuration

The [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md) (the **Clients** app in this project) handles the configuration of the io.Connect environment. The `IOBrowserPlatform()` factory function accepts an optional configuration object that allows you to enable, disable, and configure various io.Connect features. Here, you will use it to define the available Channels.

Go to the `main.jsx` file of the **Clients** app, define Channels, and extend the configuration for the internal initialization of the `@interopio/browser-platform` library:

```javascript
// Defining Channels.
const channels = {
    definitions: [
        {
            name: "Red",
            meta: {
                color: "red"
            }
        },
        {
            name: "Green",
            meta: {
                color: "green"
            }
        },
        {
            name: "Blue",
            meta: {
                color: "#66ABFF"
            }
        },
        {
            name: "Pink",
            meta: {
                color: "#F328BB"
            }
        },
        {
            name: "Yellow",
            meta: {
                color: "#FFE733"
            }
        },
        {
            name: "Dark Yellow",
            meta: {
                color: "#b09b00"
            }
        },
        {
            name: "Orange",
            meta: {
                color: "#fa5a28"
            }
        },
        {
            name: "Purple",
            meta: {
                color: "#c873ff"
            }
        },
        {
            name: "Lime",
            meta: {
                color: "#8af59e"
            }
        },
        {
            name: "Cyan",
            meta: {
                color: "#80f3ff"
            }
        }
    ]
};

// Define the configuration object and pass it to the factory function.
const config = {
    licenseKey: import.meta.env.VITE_LICENSE_KEY,
    channels
};

const settings = {
    browserPlatform: {
        factory: IOBrowserPlatform,
        config
    }
};

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <IOConnectProvider settings={settings}>
        <Clients />
    </IOConnectProvider>
);
```

When the **Clients** app starts, the defined Channels will be initialized and ready for interaction.

### 6.2. Channel Selector Widget

The users have to be able to navigate through the Channels for which they will need some sort of user interface. You can create your own Channel Selector widget by using the Channels API, but for the purpose of the tutorial, the widget is provided. To add it to the **Clients** and **Stocks** apps, follow these steps:

1. Import the Channel Selector widget in the `<Clients />` and `<Stocks />` components:

```javascript
import ChannelSelectorWidget from "./ChannelSelectorWidget";
```

2. To use the new component, you have to pass two props to it:
- `channelNamesAndColors` - the names and colors of all available Channels;
- `onChannelSelected` - handler that will be called when the Channel changes;

Go to the `io.js` files of the **Clients** and **Stocks** apps and define the following callbacks:

```javascript
// This will be used to signify that the app isn't connected to any Channel.
import { NO_CHANNEL_VALUE } from "./constants";

// Returns all names and color codes of the available Channels.
export const getChannelNamesAndColors = async (io) => {
    // Getting a list of all Channel contexts.
    const channelContexts = await io.channels.list();

    // Extracting only the names and colors of the Channels.
    const channelNamesAndColors = channelContexts.map((channelContext) => {
        const channelInfo = {
            name: channelContext.name,
            color: channelContext.meta.color
        };

        return channelInfo;
    });

    return channelNamesAndColors;
};

// This function will join the app to a Channel.
export const joinChannel = (io) => ({ value: channelName }) => {
    // Leave the current Channel when the user selects "No Channel".
    if (channelName === NO_CHANNEL_VALUE) {
        if (io.channels.my()) {
            io.channels.leave().catch(console.error);
        };
    } else {
        // Join the Channel selected by the user.
        io.channels.join(channelName).catch(console.error);
    };
};
```

3. Setup the `ChannelSelectorWidget` in both apps.

Go to the **Clients** app to set up the Channels functionalities. Import the `NO_CHANNEL_VALUE` constant that will be used for leaving the current Channel:

```javascript
import { NO_CHANNEL_VALUE } from "./constants";
import {
    getChannelNamesAndColors,
    joinChannel
} from "./io";

function Clients() {
    ...
    const channelNamesAndColors = useIOConnect(getChannelNamesAndColors);
    const onChannelSelected = useIOConnect(joinChannel);
    ...
};
```

Create the `<ChannelWidgetSelector />` component in the `return` statement. Pass `channelNamesAndColors` and `onChannelSelected` as props to it:

```javascript
return (
    <div className="container-fluid">
        <div className="row">
            ...
            <div className="col-md-8">
                <h1 className="text-center">Clients</h1>
            </div>
            <div className="col-md-2 py-2">
                <button className="btn btn-primary" onClick={onClickStocks}>Stocks</button>
            </div>
            <div className="px-3 py-1">
                <ChannelSelectorWidget
                    channelNamesAndColors={channelNamesAndColors}
                    onChannelSelected={onChannelSelected}
                />
            </div>
            ...
        </div>
        ...
    </div>
);
```

4. Go to the **Stocks** app to set up the Channels functionalities. Define a `setDefaultClient()` callback for handling the default state where no client has been selected and a `channelWidgetState` variable that will be used to trigger state change in the `<ChannelWidgetSelector />` component:

```javascript
import {
    getChannelNamesAndColors,
    joinChannel
} from "./io";

function Stocks() {
    ...
    const channelNamesAndColors = useIOConnect(getChannelNamesAndColors);
    const onChannelSelected = useIOConnect(joinChannel);
    const setDefaultClient = () => setClient({ clientId: "", clientName: "" });
    const [channelWidgetState, setChannelWidgetState] = useState(false);
    ...
};
```

Create the `<ChannelWidgetSelector />` component in the `return` statement. Pass `channelNamesAndColors` and `onChannelSelected` as props to it. Use the `onDefaultChannelSelected` property to clear the selected client and leave the current Channel when the user selects "No channel":

```javascript
return (
    <div className="container-fluid">
        <div className="row">
            ...
            <div className="col-md-8">
                <h1 className="text-center">Stocks</h1>
            </div>
            ...
            <div className="px-3 py-1">
                <ChannelSelectorWidget
                    channelNamesAndColors={channelNamesAndColors}
                    onChannelSelected={onChannelSelected}
                    onDefaultChannelSelected={setDefaultClient}
                />
            </div>
        </div>
        ...
    </div>
);
```

To leave the current Channel, re-render the Channel Selector and clear the selected client when the user clicks the "Show All" button, modify its `onClick` handler:

```javascript
onClick={() => {
    setChannelWidgetState(!channelWidgetState);
    setDefaultClient();
}}
```

Pass the `channelWidgetState` state variable to the `key` property of the `ChannelSelectorWidget` component to trigger state change:

```javascript
function Stocks() {
    ...
    return (
        <div className="container-fluid">
            <div className="row">
                ...
                <button
                    type="button"
                    className="mb-3 btn btn-primary"
                    onClick={() => {
                        setChannelWidgetState(!channelWidgetState);
                        setDefaultClient();
                    }}
                >
                    Show All
                </button>
                ...
                <div className="col-md-2 align-self-center">
                    <ChannelSelectorWidget
                        key={channelWidgetState}
                        channelNamesAndColors={channelNamesAndColors}
                        onChannelSelected={onChannelSelected}
                        onDefaultChannelSelected={setDefaultClient}
                    />
                </div>
            </div>
            ...
        </div>
    );
};
```

### 6.3. Publishing and Subscribing

Next, enable the **Clients** app to publish updates to the current Channel context and the **Stocks** app to subscribe for these updates.

Go to the `io.js` file of the **Clients** app and define a function that will publish updates to the current Channel. Use the [`publish()`](https://docs.interop.io/browser/reference/javascript/channels/api/index.md#API-publish) method and pass the selected client as an argument to update the Channel context when a new client is selected. The `publish()` method will throw an error if the app tries to publish data but isn't on a Channel. Use the [`my()`](https://docs.interop.io/browser/reference/javascript/channels/api/index.md#API-my) method to check for the current Channel:

```javascript
export const setClientPortfolioChannels = (io) => (
    {
        clientId = "",
        clientName = ""
    }
) => {
    if (io.channels.my()) {
        io.channels.publish({ clientId, clientName }).catch(console.error);
    };
};
```

Go to the `<Clients />` component and use this function to update the current Channel. Don't remove the `onClickSharedContext()` handler from the client rows. The **Stock Details** app still uses the shared context to retrieve the client information so you need to use both handlers:

```javascript
import { setClientPortfolioChannels } from "./io";

function Clients() {
    ...
    const onClickSharedContext = useIOConnect(setClientPortfolioSharedContext);
    const onClickChannel = useIOConnect(setClientPortfolioChannels);
    ...

    return (
        ...
        <tr
            key={pId}
            onClick={() => {
                    // Use both handlers.
                    onClickSharedContext({ clientId: gId, clientName: name, portfolio });
                    onClickChannel({ clientId: gId, clientName: name });
                }
            }
        >
        ...
    );
};
```

Go to the `io.js` file of the **Stocks** app and define a function that will subscribe for Channel updates:

```javascript
export const subscribeForChannels = (handler) => (io) => {
    // Subscribing for updates to the current Channel.
    io.channels.subscribe(handler);
};
```

Go to the `<Stocks />` component and comment out or delete the code that uses the Shared Contexts API to listen for updates to the shared context. Instead, subscribe for Channel updates:

```javascript
import { subscribeForChannels } from "./io";

function Stocks() {
    ...
    // useIOConnect(subscribeForSharedContext(setClient));
    useIOConnect(subscribeForChannels(setClient));
    ...
};
```

Now, when the **Clients** and the **Stocks** apps are on the same Channel, the **Stocks** app will be updated with the portfolio of the selected client.

## 7. App Management

Up until now, you had to use the Window Management API to open new windows when the user clicks on the "Stocks" button in the **Clients** app or on a stock in the **Stocks** app. This works fine for small projects, but doesn't scale well for larger ones, because this way each app must know all details (URL, start position, initial context, etc.) of every app it starts. In this chapter, you will replace the Window Management API with the [App Management API](https://docs.interop.io/browser/reference/javascript/app%20management/api/index.md) which will allow you to predefine all available apps when initializing the [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md). The **Clients** app will be decoupled from the **Stocks** app and the **Stocks** app will be decoupled from **Stock Details** - you will need only the names of the apps to be able to start them.

> ℹ️ *See also the [Capabilities > App Management](https://docs.interop.io/browser/capabilities/app-management/index.md) documentation.*

### 7.1. App Configuration

To take advantage of the [App Management API](https://docs.interop.io/browser/reference/javascript/app%20management/api/index.md), define configurations for your apps. Go to the **Clients** app and define an `applications` object containing all required definitions. Pass the `applications` object to the configuration object for the internal initialization of the `@interopio/browser-platform` library:

```javascript
// App definitions.
const applications = {
    local: [
        {
            name: "Clients",
            type: "window",
            details: {
                url: "http://localhost:3000/clients"
            }
        },
        {
            name: "Stocks",
            type: "window",
            details: {
                url: "http://localhost:3001/stocks",
                left: 0,
                top: 0,
                width: 860,
                height: 600
            }
        },
        {
            name: "Stock Details",
            type: "window",
            details: {
                url: "http://localhost:3002/details",
                left: 100,
                top: 100,
                width: 400,
                height: 400
            }
        },
        {
            name: "Client Details",
            type: "window",
            details: {
                url: "http://localhost:3003/client-details"
            }
        }
    ]
};

const config = {
    licenseKey: import.meta.env.VITE_LICENSE_KEY,
    channels,
    applications
};

const settings = {
    browserPlatform: {
        factory: IOBrowserPlatform,
        config
    }
};

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <IOConnectProvider settings={settings}>
        <Clients />
    </IOConnectProvider>
);
```

The `name` and `url` properties are required when defining an app. As you see, the position and size of the app windows is now defined in their configuration.

### 7.2. Starting Apps

Go to the `io.js` file of the **Clients** app and define a function for starting the **Stocks** app. Get the **Stocks** app object with the [`application()`](https://docs.interop.io/browser/reference/javascript/app%20management/api/index.md#API-application) method and use its [`start()`](https://docs.interop.io/browser/reference/javascript/app%20management/application/index.md#Application-start) method to start the **Stocks** app when the user clicks on the "Stocks" button. Pass the current Channel as context to the started instance:

```javascript
export const startApp = io => async () => {
    const channels = await io.channels.list();
    let channel = {};
    if (io.channels.my()) {
        const channelDefinition = channels.find(channel => channel.name === io.channels.my());
        channel = {
            name: channelDefinition.name,
            label: channelDefinition.name,
            color: channelDefinition.meta.color
        };
    } else {
        channel = {
            name: NO_CHANNEL_VALUE,
            label: NO_CHANNEL_VALUE
        }
    };
    io.appManager.application("Stocks").start({ channel });
};
```

> ⚠️ *Note that the `ChannelSelectorWidget` wraps a React `<Select />` component and to use it as a controlled component (when you want to make the **Stocks** app automatically select a Channel on startup), you must create a proper Channel definition object using the values of the `name` and `meta.color` properties and pass it to the **Stocks** app.*

Import the `startApp()` function in the `<Clients />` component, create a `startStocksApp()` callback and pass it to the `onClick` handler of the "Stocks" button:

```javascript
import { startApp } from "./io.js";

function Clients() {
    ...
    const startStocksApp = useIOConnect(startApp);
    ...

    return (
        ...
            <div className="col-md-2 py-2">
                <button className="btn btn-primary" onClick={startStocksApp}>Stocks</button>
            </div>
        ...
    )
};
```

Go to the `io.js` file of the **Stocks** app and define a function that will get the Channel passed as window context by the **Clients** app:

```javascript
export const getMyWindowContext = (setWindowContext) => async (io) => {
    const myWindow = io.appManager.myInstance;
    const context = await myWindow.getContext();

    setWindowContext({ channel: context.channel });
};
```

Go to the `<Stocks />` component, import the function and use it to set the window context:

```javascript
import { getMyWindowContext } from "./io";

function Stocks() {
    ...
    const [currentChannel, setCurrentChannel] = useState({ value: NO_CHANNEL_VALUE, label: NO_CHANNEL_VALUE });
    const [windowContext, setWindowContext] = useState({});

    useIOConnect(getMyWindowContext(setWindowContext));

    useEffect(() => {
        if (windowContext.channel) {
            setCurrentChannel(windowContext.channel);
            if (onChannelSelected) {
                onChannelSelected({ value: windowContext.channel.name });
            }
        } else {
            setCurrentChannel({ value: NO_CHANNEL_VALUE, label: NO_CHANNEL_VALUE });
        }
    }, [windowContext.channel, onChannelSelected]);
    ...
};
```

Add a `value` property to the `<ChannelSelectorWidget />` that will hold the `currentChannel` value. Add the `setCurentChannel()` function to the `onChannelSelected` property:

```javascript
function Stocks() {
    ...
    return (
        ...
        <div className="col-md-2 align-self-center">
            <ChannelSelectorWidget
                key={channelWidgetState}
                value={currentChannel}
                channelNamesAndColors={channelNamesAndColors}
                onChannelSelected={channel => {
                    onChannelSelected(channel);
                    setCurrentChannel(channel);
                }}
                onDefaultChannelSelected={channel => {
                    setDefaultClient();
                    onChannelSelected(channel);
                    setCurrentChannel({ value: NO_CHANNEL_VALUE, label: NO_CHANNEL_VALUE });
                }}
            />
        </div>
        ...
    )
};
```

The `onChannelSelected()` function manages the Channel selection and the `setCurrentChannel()` function visualizes the current Channel in the component.

### 7.3. App Instances

Go to the `io.js` file of the **Stocks** app and edit the `openStockDetails()` function. Use the [`application()`](https://docs.interop.io/browser/reference/javascript/app%20management/api/index.md#API-application) method to get the **Stock Details** app object. Check whether an instance with the selected stock has already been started by iterating over the contexts of the existing **Stock Details** instances. If there is no instance with the selected stock, call the `start()` method on the app object and pass the selected stock as a context for the started instance:

```javascript
export const openStockDetails = (io) => async (stock) => {
    const detailsApplication = io.appManager.application("Stock Details");

    // Check whether an instance with the selected stock is already running.
    const contexts = await Promise.all(
        // Use the `instances` property to get all running app instances.
        detailsApplication.instances.map(instance => instance.getContext())
    );
    const isRunning = contexts.find(context => context.stock.RIC === stock.RIC);

    if (!isRunning) {
        detailsApplication.start({ stock }).catch(console.error);
    };
};
```

Go to the `io.js` file of the **Stock Details** app and edit the `getMyWindowContext()` function to retrieve the context of the current app instance via the App Management API:

```javascript
export const getMyWindowContext = (setWindowContext) => async (io) => {
    const myWindow = io.appManager.myInstance;
    const context = await myWindow.getContext();

    setWindowContext({ stock: context.stock });
};
```

Everything works as before, the difference being that the apps now use the App Management API instead of the Window Management API.

## 8. Plugins

The developer team has decided against hard coding app definitions, as in practice it's more scalable to fetch them from a web service. The [Plugins](https://docs.interop.io/browser/capabilities/plugins/index.md) allow you to execute initial system logic contained in a custom function with access to the `io` object. You can also configure the [Main app](https://docs.interop.io/browser/developers/browser-platform/overview/index.md) whether to wait for the execution of the Plugin to complete before initialization. This will enable you to fetch and import the app definitions on startup of the Main app, but before the initialization of the [`@interopio/browser-platform`](https://www.npmjs.com/package/@interopio/browser-platform) library has completed, so that they are available to the io.Connect framework when the user starts the Main app.

> ℹ️ *See also the [Capabilities > Plugins](https://docs.interop.io/browser/capabilities/plugins/index.md) documentation.*

### 8.1. Defining a Plugin

Go to the `main.jsx` file of the **Clients** app, comment out or delete the previously declared app definitions and remove the `applications` property from the library configuration object.

Import the `setupApplications()` function from the `applicationsPlugin.js` file located in the `/plugins` folder of the **Clients** app.

Next, configure the Plugin in the Main app by using the `plugins` property of the [`@interopio/browser-platform`](https://www.npmjs.com/package/@interopio/browser-platform) configuration object. Plugins are defined in the `definitions` array of the `plugins` object. Set a name for the Plugin and pass a reference to the `setupApplications()` function in the `start` property of the Plugin object. Use the optional `config` object to pass the URL from which to fetch the app definitions. Set the `critical` property to `true` to instruct the Main app to wait for the Plugin to execute before the platform initialization completes:

```javascript
import { setupApplications } from "./plugins/applicationsPlugin";

// Define a Plugin.
const plugins = {
    definitions: [
        {
            name: "Setup Applications",
            // The REST server provides the app definitions.
            config: { url: "http://localhost:8080/api/applicationsReact"},
            start: setupApplications,
            critical: true
        }
    ]
};

// Remove the `applications` property and add `plugins`.
const config = {
    licenseKey: import.meta.env.VITE_LICENSE_KEY,
    channels,
    plugins
};

const settings = {
    browserPlatform: {
        factory: IOBrowserPlatform,
        config
    }
};

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <IOConnectProvider settings={settings}>
        <Clients />
    </IOConnectProvider>
);
```

### 8.2. Implementing a Plugin

Go to the `applicationsPlugin.js` file of the **Clients** app. The `setupApplications()` function will be the Plugin that will be executed on startup of the Main app. It will receive an initialized `io` object as a first argument and the `config` object from the Plugin definition as a second argument. Extract the URL from which to fetch the app definitions by using the `url` property of the `config` object.

In `setupApplications()`, call the `fetchAppDefinitions()` function and pass to it the URL as an argument. Store the fetched app definitions in a variable and use the [`import()`](https://docs.interop.io/browser/reference/javascript/app%20management/inmemory/index.md#InMemory-import) method of the [`inMemory`](https://docs.interop.io/browser/reference/javascript/app%20management/inmemory/index.md) object of the App Management API to [import the app definitions dynamically](https://docs.interop.io/browser/capabilities/app-management/index.md#managing_app_definitions_dynamically):

```javascript
// In `setupApplications()`.

try {
    const appDefinitions = await fetchAppDefinitions(url);

    await io.appManager.inMemory.import(appDefinitions);
} catch (error) {
    console.error(error.message);
};
```

From a user perspective, everything works as before, but by using a Plugin to fetch and import the app definitions dynamically, you have decoupled the Main app from the previously hard coded `applications` object.

## 9. Workspaces

The latest feedback from the users is that their desktops become cluttered very quickly with multiple floating windows. The **io.Connect Browser** [Workspaces](https://docs.interop.io/browser/capabilities/windows/workspaces/overview/index.md) feature solves exactly that problem.

The new requirement is that when a user clicks on a client in the **Clients** app, a new Workspace is to open displaying detailed information about the selected client in one app and their stocks portfolio in another. When the user clicks on a stock, a third app is to appear in the same Workspace displaying more details about the selected stock. You will create a **Client Details** app for displaying information about the selected client.

Remove the "Stocks" button from the **Clients** app and all logic related to it. Also remove all logic and references related to Channels from the **Clients** and **Stocks** apps that were introduced in a previous chapter. Go to the **Stock Details** app and remove the element displaying whether the selected client has the selected stock in their portfolio and all logic related to it.

Instead, you will use Workspaces to allow the users to work with multiple clients at once and organize their desktops at the same time. Channels and Workspaces can, of course, be used together to provide extremely enhanced user experience, but in order to focus entirely on working with Workspaces and the [Workspaces API](https://docs.interop.io/browser/reference/javascript/workspaces/api/index.md), the Channels functionality will be ignored.

> ℹ️ *See also the [Capabilities > Windows > Workspaces](https://docs.interop.io/browser/capabilities/windows/workspaces/overview/index.md) documentation.*

### 9.1. Setup

All Workspaces are contained in a specialized standalone web app called [Workspaces App](https://docs.interop.io/browser/capabilities/windows/workspaces/overview/index.md#workspaces_concepts-workspaces_app). It's outside the scope of this tutorial to cover building and customizing this app, so you have a ready-to-go app located at `/workspace`. The Workspaces App is already being hosted at `http://localhost:9300/`.

#### Create the Client Details App

Create a **Client Details** app that will be used for showing client information by following these steps:

- Create a new React app named `client-details` in the root directory of your **io.Connect Browser** project following the instructions in [Chapter 1.4.](#1_initial_setup-14_react_project_setup).

- Create a `ClientDetails.jsx` file in `/client-details/src` and paste the following code:

```javascript
import { useState } from "react";

function ClientDetails() {
    const [client, setClient] = useState({});

    return (
        <div className="container-fluid">
            <div className="row">
                <div className="col-md-2">
                    {!io && (
                    <span id="ioSpan" className="badge badge-warning">
                        io.Connect is unavailable
                    </span>
                    )}
                    {io && (
                    <span id="ioSpan" className="badge badge-success">
                        io.Connect is available
                    </span>
                    )}
                </div>
                <div className="col-md-10">
                    <h1 className="text-center">Client Details</h1>
                </div>
            </div>
            <div className="row">
                <div className="col-md-12">
                    <h3 id="clientStatus"></h3>
                </div>
            </div>
            <div className="row">
                <table id="clientsTable" className="table table-hover">
                    <tbody>
                        <tr>
                            <th>Full Name</th>
                            <td data-name>{client && client.clientName}</td>
                        </tr>
                        <tr>
                            <th>Address</th>
                            <td data-address>{client && client.address}</td>
                        </tr>
                        <tr>
                            <th>Phone Number</th>
                            <td data-phone>{client && client.contactNumbers}</td>
                        </tr>
                        <tr>
                            <th>Email</th>
                            <td data-email>{client && client.email}</td>
                        </tr>
                        <tr>
                            <th>Account Manager</th>
                            <td data-manager>{client && client.accountManager}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    );
};

export default ClientDetails;
```

- Go to the `main.jsx` file of the newly created **Client Details** app. Add all imports from the following example, remove the `App` import and replace the `<App />` component with `<ClientDetails />`:

```javascript
import ReactDOM from "react-dom/client";
import IOBrowser from "@interopio/browser";
import { IOConnectProvider } from "@interopio/react-hooks";
import ClientDetails from "./ClientDetails";
import "bootstrap/dist/css/bootstrap.css";

const settings = {
    browser: {
        factory: IOBrowser
    }
};

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <IOConnectProvider settings={settings}>
        <ClientDetails />
    </IOConnectProvider>
);
```

### 9.2. Workspace Layouts

A [Workspace Layout](https://docs.interop.io/browser/capabilities/windows/workspaces/overview/index.md#workspaces_concepts-workspace_layout) describes the apps participating in the Workspace and their arrangement. In a real-life scenario, Workspace Layouts, like app definitions, will most likely be fetched from a web service. Therefore, you can use another [Plugin](https://docs.interop.io/browser/capabilities/plugins/index.md) to fetch a Workspace Layout named "Client Space" that the **Clients** app will use as a blueprint for restoring a Workspace when the user clicks on a client.

> ℹ️ *For more details on using Plugins, see chapter [8. Plugins](#8_plugins).*

Go to the `main.jsx` file of the **Clients** app, import the `setupLayouts()` function from the `layoutsPlugin.js` file located in the `/plugins` folder, and define another Plugin that will fetch the Workspace Layout:

```javascript
import { setupLayouts } from "./plugins/layoutsPlugin";

const plugins = {
    definitions: [
        {
            name: "Setup Applications",
            config: { url: "http://localhost:8080/api/applicationsReact"},
            start: setupApplications,
            critical: true
        },
        {
            name: "Setup Workspace Layouts",
            config: { url: "http://localhost:8080/api/layouts"},
            start: setupLayouts,
            critical: true
        }
    ]
};

const config = { plugins };
```

Go to the `layoutsPlugin.js` file. In `setupLayouts()`, call the `fetchWorkspaceLayoutDefinitions()` function and pass to it the URL as an argument. Store the fetched Layout definitions in a variable and use the [`import()`](https://docs.interop.io/browser/reference/javascript/app%20management/inmemory/index.md#InMemory-import) method of the [Layouts API](https://docs.interop.io/browser/reference/javascript/layouts/api/index.md) to import the Workspace Layout dynamically:

```javascript
// In setupLayouts().

try {
    const layoutDefinitions = await fetchWorkspaceLayoutDefinitions(url);

    await io.layouts.import(layoutDefinitions);
} catch (error) {
    console.error(error.message);
};
```

Now, the Workspace Layout can be restored by name via the [Workspaces API](https://docs.interop.io/browser/reference/javascript/workspaces/api/index.md).

### 9.3. Initializing Workspaces

To be able to use Workspaces functionalities, initialize the [Workspaces API](https://docs.interop.io/browser/reference/javascript/workspaces/api/index.md) in the **Clients**, **Client Details** and **Stocks** apps. The **Stock Details** app will participate in the Workspace, but won't use any Workspaces functionality.

Go to the root directories of the **Clients**, **Stocks**, and **Client Details** apps and run the following command to install the Workspaces library:

```cmd
npm install @interopio/workspaces-api
```

Go to the `main.jsx` file of the **Clients** app and add the necessary configuration for initializing the Workspaces library. Provide the `IOWorkspaces()` factory function and the location of the Workspaces App:

```javascript
import IOWorkspaces from "@interopio/workspaces-api";

const config = {
    licenseKey: import.meta.env.VITE_LICENSE_KEY,
    // Provide the factory function for initializing the `@interopio/workspace-api` library.
    browser: { libraries: [IOWorkspaces] },
    // Provide the location of the Workspaces App.
    workspaces: { src: "http://localhost:9300/" },
    plugins
};

const settings = {
    browserPlatform: {
        factory: IOBrowserPlatform,
        config
    }
};

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <IOConnectProvider settings={settings}>
        <Clients />
    </IOConnectProvider>
);
```

Next, go to the `main.jsx` files of the **Client Details** and **Stocks** apps, import and provide the `IOWorkspaces()` factory function to the `libraries` array of the configuration object for initializing the [`@interopio/browser`](https://www.npmjs.com/package/@interopio/browser) library:

```javascript
import IOWorkspaces from "@interopio/workspaces-api";

const config = { libraries: [IOWorkspaces] };

const settings = {
    browser: {
        factory: IOBrowser,
        config
    }
};
```

### 9.4. Opening Workspaces

Next, implement opening a new Workspace when the user clicks on a client in the **Clients** app.

Go to the `io.js` file of the **Clients** app, define a function that will restore by name the Workspace Layout you retrieved earlier, and pass the selected client as a starting context. The specified context will be attached as window context to all windows participating in the Workspace:

```javascript
export const startAppWithWorkspace = (io) => async (client) => {
    try {
        const workspace = await io.workspaces.restoreWorkspace("Client Space", { context: client });
    } catch (error) {
        console.error(error.message);
    };
};
```

Import the function in the `<Clients />` component and create a `openWorkspace()` callback to be passed to the `onClick` handler of each client row:

```javascript
import { startAppWithWorkspace } from "./io";

function Clients() {
    ...
    const openWorkspace = useIOConnect(startAppWithWorkspace);
    ...
};
```

Delete the existing code in the `onClick` handler of the client row element and replace it with a call to `openWorkspace()`:

```javascript
...
    return (
        ...
            <tr
                key={pId}
                onClick={() => {
                    openWorkspace({ clientId: gId, clientName: name, accountManager, portfolio, ...rest });
                }}
            >
            ...
            </tr>
        ...
    );
...
```

Now, a new Workspace will open every time the user clicks on a client in the **Clients** app.

### 9.5. Starting Context

Handle the starting Workspace context to show the details and the portfolio of the selected client in the **Client Details** and the **Stocks** apps. Also, set the Workspace title to the name of the selected client.

Create an `io.js` file in the `/client-details/src` folder of the **Client Details** app and define a function that will be used for handling the details of the selected client. Use the [`onContextUpdated()`](https://docs.interop.io/browser/reference/javascript/workspaces/workspace/index.md#Workspace-onContextUpdated) method of the current Workspace to subscribe for context updates. Invoke the `setClient()` function passing the value of the updated context and set the title of the Workspace to the name of the selected client:

```javascript
export const setClientFromWorkspace = (setClient) => async (io) => {
    const myWorkspace = await io.workspaces.getMyWorkspace();
    myWorkspace.onContextUpdated((context) => {
        if (context) {
            setClient(context);
            myWorkspace.setTitle(context.clientName);
        };
    });
};
```

Import the `setClientFromWorkspace()` function in the `<ClientDetails />` component and set it up using the `useIOConnect()` hook:

```javascript
import { useIOConnect } from "@interopio/react-hooks";
import { setClientFromWorkspace } from "./io";

function ClientDetails() {
    ...
    useIOConnect(setClientFromWorkspace(setClient));
    ...
};
```

Next, go to the `io.js` file of the **Stocks** app and define a function that will be used for handling the stocks of the selected client. Use the [`onContextUpdated()`](https://docs.interop.io/browser/reference/javascript/workspaces/workspace/index.md#Workspace-onContextUpdated) Workspace method and set up the stocks for the selected client:

```javascript
export const setClientFromWorkspace = (setClient) => async (io) => {
    const myWorkspace = await io.workspaces.getMyWorkspace();
    myWorkspace.onContextUpdated((context) => {
        if (context) {
            setClient(context);
        };
    });
};
```

Import the `setClientFromWorkspace()` function in the `<Stocks />` component and set it up using the `useIOConnect()` hook:

```javascript
import { setClientFromWorkspace } from "./io";

function Stocks() {
    ...
    useIOConnect(setClientFromWorkspace(setClient));
    ...
};
```

Now, when you select a client in the **Clients** app, a new Workspace will open with the **Client Details** and the **Stocks** apps showing the relevant client information.

### 9.6. Modifying Workspaces

Next, you have to make the **Stock Details** app appear in the same Workspace as a sibling of the **Stocks** app when the user clicks on a stock. You have to check whether the **Stock Details** app has already been added to the Workspace, and if not - add it and update its context with the selected stock, otherwise - only update its context.

> ℹ️ *To achieve this functionality, you will have to manipulate a Workspace and its elements. It's recommended that you familiarize yourself with the Workspaces terminology to fully understand the following concepts and steps. Use the available documentation about [Workspaces Concepts](https://docs.interop.io/browser/capabilities/windows/workspaces/overview/index.md#workspaces_concepts), [Workspace Box Elements](https://docs.interop.io/browser/capabilities/windows/workspaces/workspaces-api/index.md#box_elements), and the [Workspaces API](https://docs.interop.io/browser/reference/javascript/workspaces/api/index.md).*

The **Stocks** app is a [`WorkspaceWindow`](https://docs.interop.io/browser/reference/javascript/workspaces/workspacewindow/index.md) that is the only child of a [`Group`](https://docs.interop.io/browser/reference/javascript/workspaces/group/index.md) element. If you add the **Stock Details** app as a child to that `Group`, it will be added as a second tab window and the user will have to manually switch between both apps. The **Stock Details** app has to be a sibling of the **Stocks** app, but both apps have to be visible within the same parent element. That's why, you have to add a new `Group` element as a sibling of the existing `Group` that contains the **Stocks** app, and then load the **Stock Details** app in it.

After the **Stocks Details** app has been opened in the Workspace as a [`WorkspaceWindow`](https://docs.interop.io/browser/reference/javascript/workspaces/workspacewindow/index.md), you have to pass the selected stock as its context. To do that, get a reference to the underlying [`WebWindow`](https://docs.interop.io/browser/reference/javascript/windows/webwindow/index.md) object of the **Stock Details** window by using the [`getGdWindow()`](https://docs.interop.io/browser/reference/javascript/workspaces/workspacewindow/index.md#WorkspaceWindow-getGdWindow) method of the [`WorkspaceWindow`](https://docs.interop.io/browser/reference/javascript/workspaces/workspacewindow/index.md) instance and update its context with the [`updateContext()`](https://docs.interop.io/browser/reference/javascript/windows/webwindow/index.md#WebWindow-updateContext) method.

Go to the `io.js` file of the **Stocks** app and define the following function:

```javascript
export const openStockDetailsInWorkspace = (io) => async (stock) => {
    // Reference to the `WebWindow` object of the Stock Details instance.
    let detailsWindow;

    const myWorkspace = await io.workspaces.getMyWorkspace();

    // Reference to the `WorkspaceWindow` object of the Stock Details instance.
    let detailsWorkspaceWindow = myWorkspace.getWindow(window => window.appName === "Stock Details");

    // Check whether Stock Details has already been opened.
    if (detailsWorkspaceWindow) {
        detailsWindow = detailsWorkspaceWindow.getGdWindow();
    } else {
        // Reference to the current window.
        const myId = io.windows.my().id;
        // Reference to the immediate parent element of the Stocks window.
        const myImmediateParent = myWorkspace.getWindow(window => window.id === myId).parent;
        // Add a `Group` element as a sibling of the immediate parent of the Stocks window.
        const group = await myImmediateParent.parent.addGroup();

        // Open the Stock Details window in the newly created `Group` element.
        detailsWorkspaceWindow = await group.addWindow({ appName: "Stock Details" });

        await detailsWorkspaceWindow.forceLoad();

        detailsWindow = detailsWorkspaceWindow.getGdWindow();
    };

    // Update the window context with the selected stock.
    detailsWindow.updateContext({ stock });
};
```

> ⚠️ *Note that [`forceLoad()`](https://docs.interop.io/browser/reference/javascript/workspaces/workspacewindow/index.md#WorkspaceWindow-forceLoad) is used to make sure that the **Stock Details** app is loaded and an [io.Connect Window](https://docs.interop.io/browser/reference/javascript/windows/webwindow/index.md) instance is available. This is necessary, because [`addWindow()`](https://docs.interop.io/browser/reference/javascript/workspaces/group/index.md#Group-addWindow) adds a new window to the [`Group`](https://docs.interop.io/browser/reference/javascript/workspaces/group/index.md) (meaning that it exists as an element in the Workspace), but it doesn't guarantee that the content has loaded.*

Import the function in the `<Stocks />` component and edit the existing `showStockDetails()` callback:

```javascript
import { openStockDetailsInWorkspace } from "./io";

function Stocks() {
    ...
    const showStockDetails = useIOConnect(openStockDetailsInWorkspace);
    ...
};
```

Go to the `io.js` file of the **Stock Details** app and change the `getMyWindowContext()` function to the following:

```javascript
export const getMyWindowContext = (setWindowContext) => async (io) => {
    const myWindow = io.windows.my();
    const context = await myWindow.getContext();

    setWindowContext({ stock: context.stock });

    myWindow.onContextUpdated((context) => {
        if (context) {
            setWindowContext({ stock: context.stock });
        };
    });
};
```

Now, when you click on a stock in the **Stocks** app, the **Stock Details** app will open below it in the Workspace showing information about the selected stocks.

## 10. Intents

A new requirement coming from the users is to implement a functionality that exports the portfolio of the selected client. Using the [Intents API](https://docs.interop.io/browser/reference/javascript/intents/api/index.md), you will instrument the **Stocks** app to raise an Intent for exporting the portfolio, and another app will perform the actual action - the **Portfolio Downloader**. The benefit of this is that at a later stage of the project, the app for exporting the portfolio can be replaced, or another app for handling the exported portfolio in a different way can also register the same Intent. In any of these cases, code changes in the **Stocks** app won't be necessary.

> ℹ️ *See also the [Capabilities > Data Sharing > Intents](https://docs.interop.io/browser/capabilities/data-sharing/intents/overview/index.md) documentation.*

### 10.1 Registering an Intent

In order for the **Portfolio Downloader** app to be targeted as an Intent handler, it must be registered as such. Apps can be registered as Intent handlers either by declaring the Intents they can handle in their app definition using the `"intents"` top-level key and supplying a handler function via the [`register()`](https://docs.interop.io/browser/reference/javascript/intents/api/index.md#API-register) method, or dynamically using only the [`register()`](https://docs.interop.io/browser/reference/javascript/intents/api/index.md#API-register) method. Using the app definition to register an Intent allows the app to be targeted as an Intent handler even if it isn't currently running. If the app is registered as an Intent handler dynamically, it can act as an Intent handler only during its life span.

The **Portfolio Downloader** app is already registered as an Intent handler in the `applicationsReact.json` file located in the `/rest-server/data` directory. The only required property is `"name"`, which holds the name of the Intent, but you can optionally specify a display name (e.g., `"Download Portfolio"`, which can later be used in a dynamically generated UI) and a context (predefined data structure, e.g. `"ClientPortfolio"`) with which the app can work:

```json
// In `applicationsReact.json`.
{
    "name": "Portfolio Downloader",
    "type": "window",
    "details": {
        "url": "http://localhost:9400/"
    },
    // Configuration for handling Intents.
    "intents": [
        {
            "name": "ExportPortfolio",
            "displayName": "Download Portfolio",
            "contexts": [
                "ClientPortfolio"
            ]
        }
    ]
}
```

Go to the `io.js` file of the **Portfolio Downloader** app. In the `setupIntentListener()` function, pass the name of the Intent and the already implemented `intentHandler()` function to the [`register()`](https://docs.interop.io/browser/reference/javascript/intents/api/index.md#API-register) method, so that it will be called whenever the **Portfolio Downloader** app is targeted as an Intent handler by the user:

```javascript
export const setupIntentListener = (setClientName) => (io) => {
    const intentHandler = (context) => {

        if (context.type !== "ClientPortfolio") {
            return;
        };

        setClientName(context.data.clientName);
        startPortfolioDownload(context.data.clientName, context.data.portfolio);
    };

    // Register the app as an Intent handler.
    io.intents.register("ExportPortfolio", intentHandler);
};
```

### 10.2 Raising an Intent

The **Stocks** app must raise an Intent request when the user clicks a button for exporting the portfolio of the selected client.

Go to the `<Stocks />` component and uncomment the "Export Portfolio" button.

Go to the `io.js` file of the **Stocks** app and define a function for raising an Intent. Perform a check whether an Intent with the name `"ExportPortfolio"` exists. If so, create an [`IntentRequest`](https://docs.interop.io/browser/reference/javascript/intents/intentrequest/index.md) object holding the name of the Intent and specifying targeting behavior and context for it. Use the [`raise()`](https://docs.interop.io/browser/reference/javascript/intents/api/index.md#API-raise) method to raise an Intent and pass the Intent request object to it:

```javascript
export const raiseExportPortfolioIntentRequest = (io) => async (portfolio, clientName) => {
    try {
        const intents = await io.intents.find("ExportPortfolio");

        if (!intents) {
            return;
        };

        const intentRequest = {
            intent: "ExportPortfolio",
            context: {
                type: "ClientPortfolio",
                data: { portfolio, clientName }
            }
        };

        await io.intents.raise(intentRequest);

    } catch (error) {
        console.error(error.message);
    };
};
```

Import the function in the `<Stocks />` component and pass it to the `useIOConnect()` hook. Store the returned handler function in a variable and assign it to the `onClick` property of the "Export Portfolio" button. Pass the portfolio and the name of the client as arguments:

```javascript
import { raiseExportPortfolioIntentRequest } from "./io";

const exportPortfolioButtonHandler = useIOConnect(raiseExportPortfolioIntentRequest);

return(
        ...
        <button
            type="button"
            className="mb-3 btn btn-primary"
            onClick={() => exportPortfolioButtonHandler(portfolio, clientName)}
        >
            Export Portfolio
        </button>
        ...
)
```

Now, clicking on the "Export Portfolio" button will start the **Portfolio Downloader** app, which will start downloading the portfolio of the currently selected client in JSON format.

## 11. Notifications

A new requirement from the users is to display a notification whenever a new Workspace has been opened. The notification must contain information for which client is the opened Workspace. Clicking on the notification must focus the Workspaces App and the Workspace for the respective client. You will use the [Notifications API](https://docs.interop.io/browser/reference/javascript/notifications/api/index.md) to raise a notification when the user clicks on a client to open a Workspace. To the notification `onclick` property, you will assign a handler for focusing the Workspaces App and the Workspace for the respective client. The handler will be invoked when the user clicks on the notification.

> ⚠️ *Note that you must allow the Main app to send notifications from the browser and also allow receiving notifications from your OS settings, otherwise you won't be able to see the raised notifications.*

> ⚠️ *Note that the notifications that will be raised won't contain action buttons. Notifications with action buttons require [configuring a service worker](https://docs.interop.io/browser/capabilities/notifications/setup/index.md#configuration), which is beyond the scope of this tutorial.*

> ℹ️ *See also the [Capabilities > Notifications](https://docs.interop.io/browser/capabilities/notifications/setup/index.md) documentation.*

### 11.1 Raising a Notification

Go to the `io.js` file of the **Clients** app and define a function for raising notifications. Define an object holding a title and body for the notification. Use the [`raise()`](https://docs.interop.io/browser/reference/javascript/notifications/api/index.md#API-raise) method to raise a notification and pass the object with options to it:

```javascript
const raiseNotificationOnWorkspaceOpen = async (io, clientName, workspace) => {
    const options = {
        title: "New Workspace",
        body: `A new Workspace for ${clientName} was opened!`,
    };

    const notification = await io.notifications.raise(options);
};
```

Next, go to the `startAppWithWorkspace()` function, modify the existing code to call this function and pass to it the `io` object, the client name and the previously obtained [`Workspace`](https://docs.interop.io/browser/reference/javascript/workspaces/workspace/index.md) object:

```javascript
// In `startAppWithWorkspace()`.
try {
    const workspace = await io.workspaces.restoreWorkspace("Client Space", restoreConfig);

    await raiseNotificationOnWorkspaceOpen(io, client.clientName, workspace);
} catch (error) {
    console.error(error.message);
};
```

Now, a notification will be raised whenever a new Workspace has been opened.

### 11.2 Notification Handler

Go to the `raiseNotificationOnWorkspaceOpen()` function and use the `onclick` property of the previously obtained [`Notification`](https://docs.interop.io/browser/reference/javascript/notifications/notification/index.md) object to assign a handler for focusing the Workspaces App and the Workspace for the respective client:

```javascript
// In `raiseNotificationOnWorkspaceOpen()`.
notification.onclick = () => {
    // This will focus the Workspaces App.
    workspace.frame.focus().catch(console.error);
    // This will focus the Workspace for the respective client.
    workspace.focus().catch(console.error);
};
```

Now, when the user clicks on a notification, the Workspaces App and the Workspace for the respective client will be focused.

## Congratulations!

You have successfully completed the **io.Connect Browser** React tutorial! See also the [JavaScript](https://docs.interop.io/browser/tutorials/javascript/index.md) and [Angular](https://docs.interop.io/browser/tutorials/angular/index.md) tutorials for **io.Connect Browser**.
