# What is ConanJs?

## The Goal

Our goal is very simple:

**To make developing end to end web applications easy and scalable.**

We focus on real use cases too, and this is why we have a [demo gallery](/tutorials/demo-gallery) where you can see how to solve some of the most common requirements using ConanJs.

**At the core, we focus on:**

* **Conan Data: With Conan data you can manage you application state, by letting you divide your state into capsules of reusable state which are ultimately plain JS objects**

To read more about how we compare to traditional state management in react, have a look at this article:

{% embed url="<https://medium.com/@owner_3186/conanjs-react-state-management-for-every-use-case-f6e95cd616a4>" %}

* **Conan Runtime: A major part of our runtime is the dependency injection, with ConanJs, in the same framework you can not only manage your state, but also have dependency injection.**

Let's look in detail at this two, Conan Data and Conan Runtime.

## **The foundation -** Conan Data and Conan Runtime

There are two pillars that build ConanJs&#x20;

### **Conan Data**&#x20;

#### **ConanJs separates the UI and the state into Conan Data.**

If you have developed web applications before, you have dealt with state.

We consider state all the changing data and metadata that you need to manage to fulfil your business requirements.

We provide you with [Conan Data](/data/general-concepts) (state and flows), which gives you a unified approach to manage the state

{% hint style="success" %}
State in ConanJs is built so that you don't have to decide what pattern to use when dealing with state.

Some of the patterns that you might be familiar and that ConanJs unifies are:

* Local state via setState / hooks / callbacks
* Context state via hooks
* Global state via Redux / Redux tool kit / selectors..

You can see this in our [scoping section](/data/conan-state/scoping-state)
{% endhint %}

### **Conan Runtime**

#### **ConanJs provides you with necessary tools to deliver enterprise grade applications**

Ultimately we want to have the state completely decoupled from the views, our end goal would be to enable developers to write their views as if they were stateless.

To help with this, and to help developers decoupling their code, we provide with [dependency injection](/dependency-injection).

We also provide with a [Logging](/logging) system that you can reuse on your app and that is used internally by everything else in ConanJs.

At last, we also provide with [ASAPs](/asaps), our own implementation of Promises which is fully compatible with your currently existing promises.

## What's next?

Still, confused? Don't blame you!

![What is ConanJs?](/files/-MBJ8K8brylt7gb4Pu8W)

It might help to look at understanding why you should use ConanJs depending on your background.

Have a look at: Why ConanJs...

{% content-ref url="/pages/-MCBl5Pl2bewdnK8sUCN" %}
[... if coming from Redux](/why-conanjs.../...-if-coming-from-redux)
{% endcontent-ref %}

{% content-ref url="/pages/-MCBwphLZeaW59sciC2N" %}
[... if using vanilla React](/why-conanjs.../...-if-using-vanilla-react)
{% endcontent-ref %}

{% content-ref url="/pages/-MCBlKzXz1lf\_0TPPo8z" %}
[... if learning React](/why-conanjs.../...-if-learning-react)
{% endcontent-ref %}

{% content-ref url="/pages/-MCCXe5BvtfSMUN3P0lf" %}
[... if not using React](/why-conanjs.../...-if-not-using-react)
{% endcontent-ref %}

You might otherwise prefer to start looking at our examples...

{% content-ref url="/pages/-MCBm6ARLgzU7DYGaZDA" %}
[Demo Gallery](/tutorials/demo-gallery)
{% endcontent-ref %}

... or maybe you prefer reading up, in which case, we would recommend start by reading about ConanData

{% content-ref url="/pages/-MCBgq-YgQkzpz4Lgdz7" %}
[General Concepts](/data/general-concepts)
{% endcontent-ref %}

## Our vision

ConanJs as of v1.0, has a lot to offer, and we think is ready to be considered as an alternative to Redux or vanilla state management.

But we think that there is a lot more that can be done.

In the next releases we will like to:

* Add support for other frameworks (Angular and Vue to start with)
* Cover more use cases in our Demos
  * Forms and validations
  * Layouts
  * Navigation
  * CRUD
* Allow for even more complex state to be created.
  * Lists
  * Streams
* Add support for transactions to our ConanData
  * Commit
  * Rollback
  * Undo/Redo...
* Reduce even further the amount of boilerplate code needed.
  * When creating async actions
  * Flows
  * Adding reactions
* Introduce the concept of resources to encapsulate the logic around fetching data.
* Provide with backend implementations to our demos to illustrate end to end scenarios

All this is to support our goal:

**To make developing end to end web applications easy and scalable.**

As you can see, we have a lot of work ahead of us.

If you like what you see, find below our About us page, and shoot us a message / github star / tweet e.t.c.&#x20;

{% content-ref url="/pages/-MBJwnb4C9WchHLMh4x3" %}
[About us / Github / Contact us](/about-us)
{% endcontent-ref %}


# Why ConanJs...


# ... if coming from Redux

If coming from Redux, we think you are going to be impressed with our Hello Wow! demo

This demo is to showcase Conan State, which are our reusable capsules of state.

{% content-ref url="/pages/-M9U259\_XPDDFTkNz0BF" %}
[Hello World](/tutorials/conan-state-demos/hello-wow)
{% endcontent-ref %}

If you are familiar with the TODO example from Redux, you might find this article also interesting:

{% embed url="<https://medium.com/conanjs/conanjs-vs-redux-comparing-a-simple-todo-app-222b87363865?source=friends_link&sk=80e501985b27f9694ac74c9bae1fbb61>" %}

Below we explore in detail the benefits of using ConanJs over Redux.

![Hi there, fellow Redux user!](/files/-MD-qg7yDz-VC1GfFuz_)

## State is easy to create

### Create simple state and actions with one line...

You can use [Conan.light](/data/conan-state/creating-state#conan-light)

### ... Or if you want to, create your own actions.

You can use [Conan.state](/data/conan-state/creating-state#conan-state) if you want to create your own custom actions.

## State is easy to update

### No need to create a pair of action/reducers

All the logic needed to update the state is encapsulated [inside the action](/data/conan-state/actions).

### No boilerplate needed to deal with async actions

[Async actions](/data/conan-state/life-cycle/async-handling) are easy to implement, and you won't need additional libraries

### No need to map dispatch to props

You can [invoke the actions directly](/data/conan-state/actions#invoking-the-actions) from the state

## State can be scoped

In ConanJs state is represented with Conan State, which ultimately is a plain JS object, which means that, as with any other object, you decide how to scope.

### You can have global scope like Redux...

Sometimes it makes sense to have [global state](/data/conan-state/scoping-state#global)

### ... or local state, if you need to

But many times, you might feel forced to add it to your global state, or you need to use other mechanisms (setState, hooks...), with ConanJs you can just make [your state local.](/data/conan-state/scoping-state#local)

## State can be composed.

### No need to map state to props

You can have you state distributed in many smaller states, and then [combine it](/data/conan-state/pipes-composing-state#two-states-to-one-state), if you need to

### No need to use selectors

You can just [filter the state](/data/conan-state/pipes-composing-state#filter), or [map it](/data/conan-state/pipes-composing-state#map)

## State can be orchestrated

### Add reactions to your state

With ConanJs is simple to write logic as a reaction to an state change, we call this [state orchestration](/data/conan-state/orchestrating-state), and it will help you building complex state interactions.

## Easy to test End to End

1\) Create state, 2) Perform any number of actions, **sync or async,** 3) Check the final value of the state. With ConanJs [end to end testing](/data/conan-state/testing) is simple

## Meaningful Logging out of the box

No need to add third party libraries to [log out what the framework is doing](/logging) behind the scenes

## More Demos

This demos will provide you with real world scenarios to use ConanJs

{% content-ref url="/pages/-MCqYpekM0o4-z8ydZqZ" %}
[Todos](/tutorials/conan-state-demos/todos)
{% endcontent-ref %}

{% content-ref url="/pages/-M9U3fePsN6qiI6QJAUJ" %}
[Github issues viewer](/tutorials/conan-state-demos/github-issues-viewer)
{% endcontent-ref %}

## And more...

If this was not enough, we  have some more features included.

{% content-ref url="/pages/-MCBXW8UgV5c6vQYrmzP" %}
[ConanFlow](/api/main-classes/conanflow)
{% endcontent-ref %}

{% content-ref url="/pages/-M9U744H3CRps68J0Tjy" %}
[Dependency Injection](/dependency-injection)
{% endcontent-ref %}

{% content-ref url="/pages/-MBYUa6Ifdga1DLBGzHx" %}
[ASAPs](/asaps)
{% endcontent-ref %}


# ... if using vanilla React

If you use Vanilla react, you are likely to have dealt with state with one or both of two main vanilla approaches.

## Vanilla state management

### Old school: setState + callback props

![Old school cool!](/files/-MD0Ibbehqaq17BYcASI)

This pattern makes sense to use when what you have to deal with is small and self contained.

The problem with this is that it doesn't scale well, if your original component uses this approach and over time it grows, you are likely to find yourself passing way too many callbacks, and to also pass them too deep in your component hierarchy.

A solution to this would be to put your state in Redux, but then you would have to deal with all the boilerplate, and you will loose the fact that this state was encapsulated in the component.

With ConanJs, you don't have to compromise, Conan State is designed to let you choose where to [scope your state](/data/conan-state/scoping-state), and makes updating the state through its out [of the box actions](/data/conan-state/actions/types-of-actions#the-default-actions) even simpler than if you were to do it with setState + callback props.

We would recommend having a look at this demo to see how to manage local state with ConanJs

{% content-ref url="/pages/-M9U259\_XPDDFTkNz0BF" %}
[Hello World](/tutorials/conan-state-demos/hello-wow)
{% endcontent-ref %}

### Cool kids: hooks + context

You might be doing React Hooks and using the React Context API as the container of your state.&#x20;

This is a very powerful pattern of which we are very fond. That is why ConanJs lets you work[ with the Context](/data/conan-state/subscribing-state/connecting) and it has its own [hooks](/data/conan-state/subscribing-state/connecting#hooks) built-in out of the box.

Basically, you can conceptually use the same approach, and yet again, make no compromises, you can still decide to use this for some state, but then, for some other state, to scope it globally because it is more sensible.

{% hint style="success" %}
With Conan State we made an effort to avoid developers making compromises.

Usually you would pick a pattern/framework or two to manage your state, and this would constraint you to a certain scope, or to a way of updating/observing your state.

With ConanJs, you pick, how to [create your state](/data/conan-state/creating-state), how to [scope it](/data/conan-state/scoping-state), how to [observe it](/data/conan-state/subscribing-state), and [how to update it](/data/conan-state/actions).
{% endhint %}

## More Demos

This demos will provide you with real world scenarios to use ConanJs

{% content-ref url="/pages/-MCqYpekM0o4-z8ydZqZ" %}
[Todos](/tutorials/conan-state-demos/todos)
{% endcontent-ref %}

{% content-ref url="/pages/-M9U3fePsN6qiI6QJAUJ" %}
[Github issues viewer](/tutorials/conan-state-demos/github-issues-viewer)
{% endcontent-ref %}

## And more...

If this was not enough, we  have some more features included.

{% content-ref url="/pages/-M9U71IjxKvtCEnma1pH" %}
[Conan Flow](/data/flows)
{% endcontent-ref %}

{% content-ref url="/pages/-M9U744H3CRps68J0Tjy" %}
[Dependency Injection](/dependency-injection)
{% endcontent-ref %}

{% content-ref url="/pages/-MBYUa6Ifdga1DLBGzHx" %}
[ASAPs](/asaps)
{% endcontent-ref %}

{% content-ref url="/pages/-MBYUiEx4KaokL8MFqon" %}
[Logging](/logging)
{% endcontent-ref %}


# ... if learning React

If you are learning React, you might also be probably learning web development, in which case, be prepared, React, or Angular or Vue... are not the only things you are going to need to learn.

Modern web development is a beast and is (in our opinion), too fragmented.

You will have to learn lots of frameworks and libraries to be able to do a simple CRUD (Create / Read / Update / Delete) application.

As our goal states,

**To make developing end to end web applications easy and scalable.**

We are trying to close this gap and to provide a framework that focuses on real world end to end cases:

![We know, you were not expecting this! Is normal to get emotional.](/files/-MD0U73kM5uitNiKuQbW)

## Where to start from?

We would suggest, as a learner, to not focus on the concepts just yet but get hands-on first.

Let's think of specific use cases where ConanJs might come in handy:

1. **I have to update some data from a button and the UI should change too**\
   [Hello Wow!](/tutorials/conan-state-demos/hello-wow)
2. **I would like to see how I can handle a little bit more interactivity, but keep it simple, no async**\
   [Todos](/tutorials/conan-state-demos/todos/todos-sync)
3. **I would like to add async actions to my app - Super easy with ConanJs!**\
   [Todos - Async](/tutorials/conan-state-demos/todos/todos-async)

{% hint style="success" %}
As of v1.0 we have demos to cover state management, but soon enough we are hoping to add more demos to cover for forms, layout, navigation, CRUD...

Stay tuned!
{% endhint %}

## Feeling more confident?

If you have played around with the demos, you should have an idea of what ConanJs is about, in which case we would recommend you to deep dive.

You can read more about Conan Data

{% content-ref url="/pages/-MCBgq-YgQkzpz4Lgdz7" %}
[General Concepts](/data/general-concepts)
{% endcontent-ref %}

Or learn about or runtime features

{% content-ref url="/pages/-M9U744H3CRps68J0Tjy" %}
[Dependency Injection](/dependency-injection)
{% endcontent-ref %}

{% content-ref url="/pages/-MBYUa6Ifdga1DLBGzHx" %}
[ASAPs](/asaps)
{% endcontent-ref %}

{% content-ref url="/pages/-MBYUiEx4KaokL8MFqon" %}
[Logging](/logging)
{% endcontent-ref %}

## Advanced demos.

{% content-ref url="/pages/-M9U3cip1z33a-FiHCQu" %}
[Todos - Optimistic](/tutorials/conan-state-demos/todos/todos-optimistic)
{% endcontent-ref %}

{% content-ref url="/pages/-M9U3fePsN6qiI6QJAUJ" %}
[Github issues viewer](/tutorials/conan-state-demos/github-issues-viewer)
{% endcontent-ref %}

{% content-ref url="/pages/-M9U3kT0hzPInUKDh8zp" %}
[Authentication](/tutorials/conan-flow-demos/authentication)
{% endcontent-ref %}


# ... if not using React

ConanJs is an agnostic framework, as of v1.0 we only have the wrappers to let you work with React, but soon enough we are hoping to cover more frameworks.

If you want to just learn about the concepts, feel free to have a look at our [Conan Data concepts](/data/general-concepts), or learn about our [Dependency Injection](/dependency-injection), [ASAPs](/asaps) or [Logging](/logging)

Feel free to [reach out to us](/about-us) if you want to receive more updates. &#x20;

![Comparing the ticket number for your framework compared to the next ticket in the pipeline](/files/-MDE_Kc-abB3yd39fA9L)


# How to install/use ConanJs

We will see now how you can start using ConanJs on our end, we will use the code from our [Hello Wow!](/tutorials/conan-state-demos/hello-wow)

## NPM

```bash
npm install conan-js-core 
```

## YARN

```bash
yarn add conan-js-core
```

## Inline JS (CDN)

```bash
https://unpkg.com/conan-js-core@1.0.0/dist/lib/main.min.js
```

## Code sandbox

You can use our Hello Wow as a starting point

{% embed url="<https://codesandbox.io/s/uzvvx>" %}

## Fork one of our examples

{% embed url="<https://github.com/conan-js/conan-js-examples>" %}

## create-react-app + Hello Wow!

If you want to start from scratch with create-react-app, this will get you the files from the [Hello Wow!](/tutorials/conan-state-demos/hello-wow) demo into a new create-react-app application with typescript.

```bash
npx create-react-app my-app --template typescript
cd my-app
yarn add conan-js-core
cd src
rm App.tsx App.test.tsx App.css
curl -o app.tsx https://raw.githubusercontent.com/conan-js/conan-js-examples/master/helloWow/src/app.tsx
curl -o index.tsx https://raw.githubusercontent.com/conan-js/conan-js-examples/master/helloWow/src/index.tsx
cd ..
yarn start
```


# About us / Github / Contact us

## Essentials

{% embed url="<https://github.com/conan-js/conan-js-core>" %}

You can contact us at:

* **twitter** to get in contact with us

{% embed url="<https://twitter.com/js_conan>" %}

* **medium**

{% embed url="<https://medium.com/@owner_3186>" %}

* **github issues** to [report bugs/feature requests](https://github.com/conan-js/conan-js-core/issues)..

## Two Albertos - 50 years of experience!

Meet Alberto Gutierrez and Alberto Almansa, 50 years of combined experience!&#x20;

First conclusion should be obvious then

![We are not exactly young....](/files/-MDF4dwAi_QYjXj3uMWw)

In these 50 years, (many of them contracting in the UK), we have done lots of different things, we have had experience fulfilling many end to end roles, from senior devs, to technical leads, architects...

We had experience in

* eCommerce (IKEA, John Lewis, LEGO...).
* Finance (Prudential, RBS, Barclays..)
* Media (Sky)
* Aviation (SITA)
* ...

And we have meaningful experience with many different technologies:

* Java
* Microservices
* Groovy
* Bash
* Oracle
* MySql
* MongoDb
* Js
* Serverless stack
* Typescript
* React
* Angular
* PHP
* Cloud architectures
* ...

## Cut to the chase!

OK, so you get it, we have been around, but mostly, we have involved for many years on end to end web applications.

Let's have a look at some facts:

* 10 years ago [Chrome was born](https://www.theverge.com/2018/9/2/17811844/google-chrome-browser-10-years-history#:~:text=Share%20All%20sharing%20options%20for,is%20now%2010%20years%20old\&text=Google%20first%20released%20its%20Chrome,the%20company's%20first%20web%20browser.)
* 7 years ago, [React was initially released](https://en.wikipedia.org/wiki/React_\(web_framework\))
* Around 5 years ago, [Redux was released](https://www.smashingmagazine.com/2016/06/an-introduction-to-redux/)
* This year, Microsoft announced that [their new IE version would be based on Chromium](https://www.theverge.com/2020/1/15/21066767/microsoft-edge-chromium-new-browser-windows-mac-download-os)

JS, and full stack developers are in high demand:

{% embed url="<https://insights.stackoverflow.com/survey/2019#technology>" %}

{% embed url="<https://octoverse.github.com/>" %}

{% embed url="<https://www.infoworld.com/article/3515788/javascript-is-the-most-in-demand-it-skill.html>" %}

There are many more articles that we could link that will support what we think is something that pretty much everyone with experience in the industry will agree with.

**JS is the hottest and more exciting platform to be working as a developer at the moment**

Note that this statement is not meant to start a holy war around which language is best. We put the emphasis on JS as a platform, not a language, let's see why:

* Browsers have matured to a stage where they can support most enterprise requirements
* Cloud infrastructure and SaaS are allowing the integration of services and deployment to a degree never seen before.
* Internet access is ubiquitous.

**All together, it makes for an ecosystem where JS is the de facto runtime language to support enterprise requirements.**

This is still an ongoing process where most companies have been caught migrating their old desktop apps to the browser, or learning how to develop them for their new applications.

While the advent of new UI frameworks is and obvious step on the right direction to provide with tools for developers to deliver these requirement, we also think that they are overlooking other areas from a web app that should be agnostic to the UI framework of your choice.

**In ConanJs we try to cover the technology gap between enterprise requirements and UI frameworks by providing with the tools necessary to manage the state, and the runtime separately from the UI.**

## Meet the Albertos!

In the following picture you can find:

* The two Albertos that have perpetrated this framework.
* A bonus Alberto Jr.
* The missuses.
* A little boy which middle name is Conan (not kidding).
* Bonus, not in the picture: (She was still in daddy's pipeline). A little girl which middle name is Xena (again, not kidding)

![](/files/-MDFuHvPlMAULWSKvRDo)


# Demo Gallery

## Hello world

The simplest example that we could think of that uses ConanState

{% content-ref url="/pages/-M9U259\_XPDDFTkNz0BF" %}
[Hello World](/tutorials/conan-state-demos/hello-wow)
{% endcontent-ref %}

## **Todo app**

{% content-ref url="/pages/-MCqYpekM0o4-z8ydZqZ" %}
[Todos](/tutorials/conan-state-demos/todos)
{% endcontent-ref %}

These are the recommended demos if you are new to Conan and would like to go past just learning the concepts, it walks you through three increasingly complex use cases for the todo app.

![The end game of the todo App, is optimistic updates.](/files/-MCpttcJvXI-ZrHDKrNt)

## Github issues viewer app.

{% content-ref url="/pages/-M9U3fePsN6qiI6QJAUJ" %}
[Github issues viewer](/tutorials/conan-state-demos/github-issues-viewer)
{% endcontent-ref %}

This demo is meant to showcase a slightly more real use case that the Todo app, ultimately you will be able to leverage the github APIS to create your own github frontend.

![Create you own Github frontend](/files/-MCqKoj9p3LjrqskC4sM)

## Authentication

{% content-ref url="/pages/-M9U3kT0hzPInUKDh8zp" %}
[Authentication](/tutorials/conan-flow-demos/authentication)
{% endcontent-ref %}

The demo around Conan Flow highlights how the authentication flow can be easily mapped with a Conan Flow

![](/files/-MCqFsj0HmQ1cQ4nQeEb)


# Conan State Demos

## Docs

* [Conan State](/data/conan-state)
* [Dependency Injection](/dependency-injection)

## Hello World

### Highlights

* Simplest possible example we could think to showcase Conan State

{% content-ref url="/pages/-M9U259\_XPDDFTkNz0BF" %}
[Hello World](/tutorials/conan-state-demos/hello-wow)
{% endcontent-ref %}

## Todos App

### Todos

#### Highlights

* Simple application, no async operations
* Uses dependency injection to scope the state.
* Connects data using React components.

{% content-ref url="/pages/-M9U3VdgOI63wzcbKcEL" %}
[Todos - Basic](/tutorials/conan-state-demos/todos/todos-sync)
{% endcontent-ref %}

### Todos - Async

#### Highlights

* Simplest async demo.
* Uses dependency Injection to scope the state and a service
* Uses auto-bind to connect the service to the state.
* Builds up from the code used in the Todos demo

{% content-ref url="/pages/-M9U3Z3tCbIdWDOhZPx7" %}
[Todos - Async](/tutorials/conan-state-demos/todos/todos-async)
{% endcontent-ref %}

### Todos - Optimistic

#### Highlights

* Advanced async demo, it showcases the potential of ConanJs to let you perform optimistic async operations
* Builds up from the code used in the Todos  - Async demo

{% content-ref url="/pages/-M9U3cip1z33a-FiHCQu" %}
[Todos - Optimistic](/tutorials/conan-state-demos/todos/todos-optimistic)
{% endcontent-ref %}

## Github Issues Viewer

Highlights

* Uses real endpoints to fetch data.
* Uses react hooks to observe the data

{% content-ref url="/pages/-M9U3fePsN6qiI6QJAUJ" %}
[Github issues viewer](/tutorials/conan-state-demos/github-issues-viewer)
{% endcontent-ref %}


# Hello World

Have a look at the simplest example with Conan State.

This is our attempt to wow you, note that this is only a sample of all the different ways to work with ConanState

### Easy to create and render

[To create a Conan State](/data/conan-state/creating-state) you only need a name, and optionally, an initial state

```typescript
//name: counter, initialState: 0
const yetAnotherCounter$ = Conan.light('counter', 0)
```

Conan has [live rendering](/data/conan-state/subscribing-state/live-rendering), meaning, you can inline the state in your renderer.

```typescript
function render() {
    return yetAnotherCounter$.renderLive (
        (counterValue)=>(<h1>{counterValue}</h1>)
    )
}

```

### Easy to update

Every ConanState has two actions available immediately: 'update' and  'updateAsap'.

Let's add some buttons now tow change the state of the counter:

```typescript
function render() {
    return (<div>
        yetAnotherCounter$.renderLive (
            (counterValue)=>(<h1>{counterValue}</h1>)
        )
        <button onClick={()=>yetAnotherCounter$.do.update(3)}>
            setValueTo3
        </button>
        <button onClick={()=>yetAnotherCounter$.do.update(current=>++current)}>
            increase by one
        </button>
    </div>)
}

```

Note how we can use the update method to either provide a new value, or we can provide a reducer to provide a value that is based on its current value.

### Easy to do async updates

Quick fact, with ConanJs you won't need boilerplate code to deal with asynchronous code.&#x20;

![You are probably speechless now...](/files/-MBJtnjV_M2CG66AW10h)

Let's add two buttons to show async updates to the value.

```typescript
function render() {
    return (<div>
        yetAnotherCounter$.renderLive (
            (counterValue)=>(<h1>{counterValue}</h1>)
        )
        <button onClick={()=>yetAnotherCounter$.do.update(3)}>
            setValueTo3
        </button>
        <button onClick={()=>yetAnotherCounter$.do.update(current=>++current)}>
            increase by one
        </button>
        <button onClick={()=>yetAnotherCounter$.do.updateAsap(
            Asaps.delayed(3, 1000)
        )}>
            setValueTo3 - asnyc
        </button>
        <button onClick={()=>yetAnotherCounter$.do.updateAsap(
            Asaps.delayed(current=>++current, 1000)
        )}>
            increase by one - async
        </button>

    </div>)
}
```

### Easy to derive and compose state

Let's filter only even numbers, and double the current value of the state

```
<h1>
    EVEN NUMBERS: {yetAnotherCounter$.filter(it=>it % 2 === 0).connectLive (
        (counterValue)=>(<span>{counterValue}</span>)
    )}
</h1>
<h1>
    DOUBLE: {yetAnotherCounter$.map(it=>it * 2).connectLive (
        (counterValue)=>(<span>{counterValue}</span>)
    )}
</h1>
```

## Demo

{% embed url="<https://codesandbox.io/s/uzvvx>" %}

## �What's next?

In ['How to install/use ConanJs'](/how-to-install-use-conanjs) we will show you how to get this code running on your end.

{% hint style="info" %}
&#x20;Are you ready to dive in?&#x20;

Yes, show me more code!  <https://docs.conanjs.io/tutorials/todos-sync>

Yes, I prefer reading up! <https://docs.conanjs.io/conan-state>

Just let me know how to start using it! <https://docs.conanjs.io/how-to-install-use-conanjs>

NO! :(  Would you mind [reaching out to us](/about-us) to let us know how we can improve?
{% endhint %}


# Todos


# Todos - Basic

A step by step guide to create a Todos application with ConanJs

In ConanJs we wanted to be original, and we have decided to start showing how to build a list of Todos in our first tutorial. We will then go a bit further than other frameworks do, and will show how we can add Asynchronous calls and optimistic updates.

The code for this example is available at GitHub:

{% embed url="<https://github.com/conan-js/conan-js-examples/tree/master/todo-list>" %}

and you can also check this [code sandbox](/tutorials/conan-state-demos/todos/todos-sync#code-sandbox) at the bottom of this page.

If you are coming from Redux, you might want to see how this compares to the TODO from Redux, if that is the case, have a look at this article:

{% embed url="<https://medium.com/conanjs/conanjs-vs-redux-comparing-a-simple-todo-app-222b87363865?source=friends_link&sk=80e501985b27f9694ac74c9bae1fbb61>" %}

## Initial steps

### Adding ConanJs to the project

In the project root, just run:

```typescript
npm install conan-js-core
```

## Implementing the Todos app

### Domain model

{% hint style="success" %}
Our examples are in typescript, if you use javascript, you can just ignore the type definitions and it will all work just fine on your end.

The following interfaces are to define with Typescript the domain for the application.
{% endhint %}

Our data structure for this example will be very straightforward, simply having a Todo, TodoList and status entities. We will also model the visibility filters as:

```typescript
export enum ToDoStatus {
    PENDING = 'PENDING',
    COMPLETED = 'COMPLETED'
}

export interface ToDo {
    id: string;
    description: string;
    status: ToDoStatus;
}

export enum VisibilityFilters {
    SHOW_ALL = 'SHOW_ALL',
    SHOW_COMPLETED = 'SHOW_COMPLETED',
    SHOW_ACTIVE = 'SHOW_ACTIVE'
}

export interface TodoListData {
    todos: ToDo[];
    appliedFilter: VisibilityFilters;
}
```

### Creating the Todos state

To create the state we will use [Conan.state](broken://pages/-M9U5DrZcDOwWFWdbB2R) as we will need to pass our custom reducers later on. The data part of our state will be represented by the *TodoListData,* which holds an array of Todos and a current applied filter. We are initially just passing one reducer to add a Todo to the current array of todos.

{% tabs %}
{% tab title="Js" %}

```javascript
export const todoListSyncState$ = Conan.state({
    name: 'todos-sync',
    initialData: {
        appliedFilter: VisibilityFilters.SHOW_ALL,
        todos: []
    },
    reducers: ({
        $addTodo: (todo) => ({
            todos: [...getState().todos, todo],
            appliedFilter: getState().appliedFilter
        })
    }),
});
```

{% endtab %}

{% tab title="Ts" %}

```typescript
export type TodoListState = ConanState<TodoListData>;


export const todoListSyncState$: TodoListState  = Conan.state<TodoListData>({
    name: 'todos-sync',
    initialData: {
        appliedFilter: VisibilityFilters.SHOW_ALL,
        todos: []
    },
    reducers: getState => ({
        $addTodo: (todo: ToDo): TodoListData => ({
            todos: [...getState().todos, todo],
            appliedFilter: getState().appliedFilter
        })
    }),
});
```

{% endtab %}
{% endtabs %}

Let's add our newly defined state to [Conan Dependency Injection](/dependency-injection), so that is accesible from all the app.

{% tabs %}
{% tab title="Js" %}

```javascript
export let diContext = DiContextFactory.createContext({
    todoListState: todoListSyncState$,
});
```

{% endtab %}

{% tab title="Ts" %}

```typescript
export let diContext: App = DiContextFactory.createContext<App>({
        todoListState: todoListSyncState$,
    }
);
```

{% endtab %}
{% endtabs %}

###

### Connecting the state

To use our new reducer and add a Todo, we just need to connect our presentation components with Conan state. For a guide on the different ways of connecting the state please visit [Using the State](/data/conan-state/subscribing-state)

For this example we will use Conan HOC [StateConnect](/data/conan-state/subscribing-state):

{% tabs %}
{% tab title="Js" %}

```javascript
<StateConnect from={diContext.todoListState} into={TodoListRenderer} 
    fallbackValue={{
            todos: [],
            appliedFilter: VisibilityFilters.SHOW_ALL
}}/>
```

{% endtab %}

{% tab title="Ts" %}

```typescript
<StateConnect<TodoListData, TodoListActions>
    from={diContext.todoListState}
    into={TodoListRenderer}
    fallbackValue={{
        todos: [],
        appliedFilter: VisibilityFilters.SHOW_ALL
    }}
/>
```

{% endtab %}
{% endtabs %}

{% hint style="success" %}
As we have added our state to Conan DI, we can just use it with ***diContext.todoListState***
{% endhint %}

### Adding a Todo

To add a Todo, *TodoListRenderer* can now make use of our state data and actions. It can now include the AddTodo component and pass the action addTodo created by ConanJs, from the reducer we created before:

```javascript
<AddTodo onClick={actions.addTodo}/>
```

### �Toggling a Todo

To toggle a Todo we will add a new reducer to the Conan state, and pass it in the reducers input parameter:

{% tabs %}
{% tab title="Js" %}

```javascript
$toggleTodo: (toggledTodo) => ({
        todos: getState().todos.map(todo => todo.id !== toggledTodo.id ? todo : {
            ...todo,
            status: (todo.status === ToDoStatus.PENDING ? ToDoStatus.COMPLETED : ToDoStatus.PENDING)
        }),
        appliedFilter: getState().appliedFilter
}),
```

{% endtab %}

{% tab title="Ts" %}

```typescript
$toggleTodo: (toggledTodo: ToDo): TodoListData => ({
        todos: getState().todos.map(todo =>
            todo.id !== toggledTodo.id ? todo : {
                ...todo,
                status: (todo.status === ToDoStatus.PENDING ? ToDoStatus.COMPLETED : ToDoStatus.PENDING)
            },
        ),
        appliedFilter: getState().appliedFilter
})
```

{% endtab %}
{% endtabs %}

TodoListRenderer can now render the list of Todos and pass the action to toggle them:

{% tabs %}
{% tab title="Js" %}

```javascript
<ul>
    (data.todos).map(todo => 
    <Todo key={todo.id} onClick={() => actions.toggleTodo(todo)} 
        text={todo.description} completed={todo.status === ToDoStatus.COMPLETED}/>)}
</ul>
```

{% endtab %}

{% tab title="Ts" %}

```typescript
{filterToDos(data.todos, data.appliedFilter).map(todo =>
    <Todo
        key={todo.id}
        onClick={() => actions.toggleTodo(todo)}
        text={todo.description}
        completed={todo.status === ToDoStatus.COMPLETED}
    />
)}
```

{% endtab %}
{% endtabs %}

### �Filtering Todos

Let's add the last reducer to the Conan state in order to filter Todos:

{% tabs %}
{% tab title="Js" %}

```javascript
$filter: (filter) => ({
    todos: getState().todos,
    appliedFilter: filter
})
```

{% endtab %}

{% tab title="Ts" %}

```typescript
$filter: (filter: VisibilityFilters): TodoListData => ({
    todos: getState().todos,
    appliedFilter: filter
})
```

{% endtab %}
{% endtabs %}

TodoListRenderer can now pass the filter action to the Footer component:

```javascript
<FooterRenderer appliedFilter={data.appliedFilter} filterUpdater={actions.filter}/>
```

We can use the current filter now to only show the correct Todos:

{% tabs %}
{% tab title="Js" %}

```javascript
<ul>
    {filterToDos(data.todos, data.appliedFilter).map(todo => <Todo key={todo.id} onClick={() => actions.toggleTodo(todo)} text={todo.description} completed={todo.status === ToDoStatus.COMPLETED}/>)}
</ul>

export function filterToDos(todos, filter) {
    switch (filter) {
        case VisibilityFilters.SHOW_ALL:
            return todos;
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter(t => t.status === ToDoStatus.COMPLETED);
        case VisibilityFilters.SHOW_ACTIVE:
            return todos.filter(t => t.status === ToDoStatus.PENDING);
        default:
            throw new Error('Unknown filter: ' + filter);
    }
}
```

{% endtab %}

{% tab title="Ts" %}

```typescript
<ul>
    {filterToDos(data.todos, data.appliedFilter).map(todo =>
        <Todo
            key={todo.id}
            onClick={() => actions.toggleTodo(todo)}
            text={todo.description}
            completed={todo.status === ToDoStatus.COMPLETED}
        />
    )}
</ul>

export function filterToDos(todos: ToDo[], filter: VisibilityFilters): ToDo[] {
    switch (filter) {
        case VisibilityFilters.SHOW_ALL:
            return todos;
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter(t => t.status === ToDoStatus.COMPLETED);
        case VisibilityFilters.SHOW_ACTIVE:
            return todos.filter(t => t.status === ToDoStatus.PENDING);
        default:
            throw new Error('Unknown filter: ' + filter);
    }
}
```

{% endtab %}
{% endtabs %}

## Code sandbox

All the files needed for this example are available in this codesandbox. Please be aware that although we explain the stops in both Javascript and Typescript, our examples are written in Typescript.

{% embed url="<https://codesandbox.io/s/ve8zx>" %}


# Todos - Async

Let's add some asynchronous calls to the previous Todos example

### Introduction

State management usually gets very complicated when we need to build a realistic app, that for instance needs to make calls to a server API, therefore it needs to integrate the state with asynchronous calls. For this example we will use Conan's *autoBind* feature, which is fully described under [Conan asynchronous state](broken://pages/-M9sjuF--Cq3HxHBZoZM)

### Adding async calls

Let's say our Todo app needs to make an API call to fetch the current todos, and to add and toggle a todo. We could easily think of embedding that logic in its own service class. We could model that as:

{% tabs %}
{% tab title="Js" %}

```javascript
export class TodoListServiceImpl {
    fetch() {
        return Asaps.delayed([{ description: 'test', id: '-1', status: ToDoStatus.PENDING }], 500, 'fetch');
    }
    addTodo(todo) {
        return Asaps.delayed(todo, 5000, 'addTodo');
    }
    toggleTodo(todo) {
        return Asaps.delayed(todo, 1000, 'toggleTodo');
    }
}
```

{% endtab %}

{% tab title="Ts" %}

```typescript
export interface TodoListService {
    fetch(): Asap<ToDo[]>;

    addTodo(todo: ToDo): Asap<ToDo>;

    toggleTodo(todo: ToDo): Asap<ToDo>;
}

export class TodoListServiceImpl implements TodoListService {
    public fetch(): Asap<ToDo[]> {
        return Asaps.delayed([{description: 'test', id: '-1', status: ToDoStatus.PENDING}], 500, 'fetch');
    }

    public addTodo(todo: ToDo): Asap<ToDo> {
        return Asaps.delayed(todo, 5000, 'addTodo');
    }

    public toggleTodo(todo: ToDo): Asap<ToDo> {
        return Asaps.delayed(todo, 1000, 'toggleTodo');
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
We are just simulating the API calls with a delayed Asap
{% endhint %}

{% hint style="success" %}
Note the function names match the reducers names, therefore ConanJs will bind each funcrion with its corresponding reducer
{% endhint %}

### Creating the state

As mentioned above we will be using autoBind, passing the todoListSevice implementation:

{% tabs %}
{% tab title="Js" %}

```javascript
export class TodoListAsyncStateFactory {
    static create(todoListService) {
        return Conan.state({
            name: 'todos-async',
            initialData: {
                appliedFilter: VisibilityFilters.SHOW_ALL,
                todos: []
            },
            reducers: TodoListReducersFn,
            autoBind: todoListService
        });
    }
}
```

{% endtab %}

{% tab title="Ts" %}

```typescript
export class TodoListAsyncStateFactory {
    static create(todoListService: TodoListService): TodoListState {
        return Conan.state<TodoListData, TodoListReducers>({
            name: 'todos-async',
            initialData: {
                appliedFilter: VisibilityFilters.SHOW_ALL,
                todos: []
            },
            reducers: TodoListReducersFn,
            autoBind: todoListService
        })
    }
}
```

{% endtab %}
{% endtabs %}

�As in the Todos example, Conan's DI will hold the definition of the state, but in this example it will instantiate the async one we have just described.

{% tabs %}
{% tab title="Js" %}

```javascript
export let diContext = DiContextFactory.createContext({
    todoListState: TodoListAsyncStateFactory.create,
}, {
    todoListService: TodoListServiceImpl
});
```

{% endtab %}

{% tab title="Ts" %}

```typescript
export let diContext = DiContextFactory.createContext<App, InternalDependencies>({
        todoListState: TodoListAsyncStateFactory.create,
    }, {
        todoListService: TodoListServiceImpl
    },
);
```

{% endtab %}
{% endtabs %}

�This is all that is needed to bring asynchronous behaviour into ConanJs's state, the rest of the code is the same as the simple Todos example.&#x20;

### Getting the code

Please feel free to download the example at:&#x20;

{% embed url="<https://github.com/conan-js/conan-js-examples/tree/master/todo-list-async>" %}

or just play with it in the code sandbox.

### Code sandbox

{% embed url="<https://codesandbox.io/s/o0cxv>" %}
TODOs with async actions
{% endembed %}


# Todos - Optimistic

What if we wanted to optimistically add/toggle our todos before the server API call returns?

### Introduction

ConanJs allows you to add *optimistic* updates to your state. In order to achieve this, it provides State [monitor](broken://pages/-M9sjuF--Cq3HxHBZoZM) and [asyncMerge](broken://pages/-M9sjuF--Cq3HxHBZoZM).  As you will see, the monitor also allows us to cancel ongoing async calls, and update our local state accordingly.

### Adding the state&#x20;

We need to slightly modify our Todo definition to make it optimistically updatable. It just needs to hold a status per todo item:

```typescript
export enum OptimisticStatus {
    SETTLED = 'SETTLED',
    IN_PROCESS = 'IN_PROCESS',
}

export interface OptimisticData<T> {
    data: T;
    status: OptimisticStatus;
    cancelCb: ICallback;
}

export interface OptimisticTodoListData {
    todos: OptimisticData<ToDo>[];
    appliedFilter: VisibilityFilters;
}
```

�Now we will enrich our app with a new optimistically updatable state. For that in our Conan's DI definition file, we have to add:

```typescript
export interface OptimisticApp extends App {
    optimisticTodoListState: ConanState<OptimisticTodoListData, TodoListActions>
}

export let diContext = DiContextFactory.createContext<OptimisticApp, InternalDependencies>({
        todoListState: TodoListAsyncStateFactory.create,
        optimisticTodoListState: OptimisticTodoListData$
    }, {
        todoListService: TodoListServiceImpl
    },
);
```

### �Implement optimistic updates

The key part here is how the optimisticTodoListState is created, as it is in fact a merged state of the state's monitor info and the state's data:

```typescript
export function OptimisticTodoListData$(todoListState: TodoListState): ConanState<OptimisticTodoListData, TodoListActions> {
    return todoListState.asyncMerge<OptimisticTodoListData>(
        {
            appliedFilter: VisibilityFilters.SHOW_ALL,
            todos: []
        },
        (monitorInfo, data, current) => {
            if (monitorInfo.currentAction == null) {
                return current;
            }

            let asyncTodo: ToDo = monitorInfo.currentAction.payload [0];
            if (monitorInfo.status === MonitorStatus.ASYNC_CANCELLED) {
                return ({
                    appliedFilter: current.appliedFilter,
                    todos: current.todos.filter(it => it.data.id !== asyncTodo.id)
                })
            }

            if (monitorInfo.status !== MonitorStatus.ASYNC_START) {
                return current;
            }

            return monitorInfo.currentAction.name === 'addTodo' ? {
                appliedFilter: current.appliedFilter,
                todos: [...current.todos, {
                    status: OptimisticStatus.IN_PROCESS,
                    data: asyncTodo,
                    cancelCb: () => {
                        if (monitorInfo.currentAction == null) {
                            throw new Error(`unexpected error`);
                        }

                        monitorInfo.currentAction.asap.cancel()
                    }
                }]
            } : monitorInfo.currentAction.name === 'toggleTodo' ? {
                    appliedFilter: current.appliedFilter,
                    todos: current.todos.map(todo => todo.data.id !== asyncTodo.id ? todo : {
                        status: OptimisticStatus.IN_PROCESS,
                        data: {
                            ...asyncTodo
                        },
                        cancelCb: () => {
                            if (monitorInfo.currentAction == null) {
                                throw new Error(`unexpected error`);
                            }

                            monitorInfo.currentAction.asap.cancel()
                        }
                    })
                } :
                current
        },
        (data, monitorInfo, optimisticData) => ({
            appliedFilter: data.appliedFilter,
            todos: Lists.mergeCombine(
                data.todos,
                optimisticData.todos,
                (todo, optimisticTodo) => todo.id === optimisticTodo.data.id,
                (todo) => ({
                    status: OptimisticStatus.SETTLED,
                    data: todo,
                    cancelCb: () => {
                    }
                })
            )
        })
    )
}
```

### �Adding cancellation

As the app can now access a merged state that also contains the monitor actions, it can invoke the cancel action. For example, we have slightly modified the Todo react component, to include a **loading**... and a **cancel button**:

```typescript
interface TodoProps {
    toggleCb: ICallback;
    completed: boolean;
    text: string;
    status: OptimisticStatus,
    cancelCb: ICallback,
    id: string
}

export class OptimisticTodo extends React.Component<TodoProps> {
    render() {
        return (
            <li
                key={this.props.id}
                style={{
                    textDecoration: this.props.completed ? 'line-through' : 'none'
                }}
            >
                {this.props.text} <button onClick={this.props.toggleCb}>toggle</button>{this.props.status === OptimisticStatus.IN_PROCESS &&
                    <>'  ...LOADING!...' <button onClick={this.props.cancelCb}>cancel</button></>
                }
            </li>
        );
    }
}
```

### Getting the code�

Please feel free to visit our examples at:

{% embed url="<https://github.com/conan-js/conan-js-examples/tree/master/todo-list-optimist>" %}

or the code sandbox below, for more details on this ConanJs feature.

### Code sandbox

{% embed url="<https://codesandbox.io/s/chzft>" %}
These TODOs are very optimistic!
{% endembed %}


# Github issues viewer

Let's use ConanJs to build a realistic app that browses a remote repository

### Introduction

We used this example to experiment with defining different isolated states and show how they can be used together when different asynchronous calls are needed. In this section we have only shown the code in Typescript.

### Creating the Conan states

We have divided the data handled by the app into four independent states:

The remote repository connection details is called *repoState$*:

```typescript
export const repoState$: RepoState = 
        Conan.light<RepoData>('repo', {org: "rails", repo: "rails", page: 1})
```

The specific repository data information retrieved is modelled in *repoDetailsState$ :*

```typescript
export interface RepoDetailsData {
    openIssuesCount: number
    error: string | null
}

export const repoDetailsState$: RepoDetailsState = Conan.state<RepoDetailsData>({
    name: 'repo-details',
    initialData: {openIssuesCount: -1, error: null},
    reducers: repoDetailsReducersFn,
    actions: repoDetailsActionsFn
});
```

The issues data is modelled in *issuesState$*:

```typescript
export type IssuesState = ConanState<IssuesData, IssuesActions>;

export interface IssuesData {
    issuesByNumber: Record<number, Issue>;
    issues: Issue[];
    issueId?: number;
    displayType: 'issues' | 'comments';
}

export const issuesState$: IssuesState = Conan.state<IssuesData, IssuesReducers, IssuesActions>({
    name: 'issues',
    initialData: {
        issuesByNumber: {} as Record<number, Issue>,
        issues: [],
        displayType: "issues"
    },
    reducers: issuesReducersFn,
    actions: issueActionsFn
})
```

�and finally the issues comments is modelled in *issuesCommentsState$*:

```typescript
export interface IssuesCommentsData {
    commentsByIssue: Record<number, IssueComment[] | undefined>
}

export type IssuesCommentsState = ConanState<IssuesCommentsData, IssuesCommentsActions>;

export const issuesCommentsState$: IssuesCommentsState = Conan.state<IssuesCommentsData, IssuesCommentsReducersFn, IssuesCommentsActions>({
    name: 'issues-comments',
    initialData: {
        commentsByIssue: {} as Record<number, IssueComment[]>,
    },
    reducers: issuesCommentsReducers,
    actions: issueCommentsActionsFn
})
```

### �Adding async operations

In this app we need to fetch the issues of a given repository, fetch the information of that same repository and finally retrieve the comments of a given issue. We have implemented this logic in a service called *IssuesServiceImpl* which uses [ConanJs Asap](broken://pages/-M9sjuF--Cq3HxHBZoZM#asap) to implement the asynchronous calls:

```typescript
export interface IssuesService {
    fetch(repo: string, org: string, page: number): Asap<Issue[]>;

    fetchComments(commentsUrl: string): Asap<IssueComment[]>;

    fetchRepoDetails(org: string, repo: string): Asap<RepoDetails>;
}

export class IssuesServiceImpl implements IssuesService {
    fetch(repo: string, org: string, page: number = 1): Asap<Issue[]> {
        return Asaps.fetch<Issue[]>(`https://api.github.com/repos/${org}/${repo}/issues?per_page=25&page=${page}`);
    }

    fetchComments(commentsUrl: string): Asap<IssueComment[]> {
        return Asaps.fetch<IssueComment[]>(commentsUrl);
    }

    fetchRepoDetails(org: string, repo: string): Asap<RepoDetails> {
        return Asaps.fetch(`https://api.github.com/repos/${org}/${repo}`);
    }
}
```

### �Adding DI dependencies

We have made these states and the service available to all the app via [ConanJs DI](/dependency-injection):

```typescript
interface AuxDependencies {
    issuesService: IssuesService
}

export let diContext = DiContextFactory.createContext<App, AuxDependencies>(
    {
        issuesCommentsState: issuesCommentsState$,
        issuesState: issuesState$,
        repoState: repoState$,
        repoDetailsState: repoDetailsState$
    }, {
        issuesService: IssuesServiceImpl
    }
);

export interface App {
    issuesState: IssuesState;
    issuesCommentsState: IssuesCommentsState;
    repoState: RepoState;
    repoDetailsState: RepoDetailsState;
}
```

### �Fetching the issues

We need to implement an async call to retrieve the issues of the repository given. We can see how that is done in the actions passed to ***issuesState$**:*

```typescript
export interface IssuesActions {
    fetch(repo: string, org: string, page: number): Asap<IssuesData>;

    fetchIssue(issueId: number): IssuesData;

    showIssues(): IssuesData;
}


export const issueActionsFn: ActionsFn<IssuesData, IssuesReducers, IssuesActions> = thread => ({
    fetch(repo, org, page): Asap<IssuesData> {
        return thread.monitor(
            diContext.issuesService.fetch(repo, org, page).catch(() => thread.reducers.$fetch([])),
            (issues, reducers) => reducers.$fetch(issues as Issue[]),
            'fetch',
            [repo, org, page]
        )
    },
    fetchIssue(issueId: number): IssuesData {
        return thread.reducers.$fetchIssue(issueId);
    },
    showIssues(): IssuesData {
        return thread.reducers.$switchDisplay("issues");
    }
})
```

{% hint style="info" %}
The fist action fetch has the async call, so it's wrapped with thread.monitor. The other 2 actions are synchronous, so they can just call the reducer
{% endhint %}

{% hint style="success" %}
we can access the *issuesService* from anywhere, since it's defined in ConanJs DI
{% endhint %}

### Fetching the repository information

We need another async call to retrieve the repository information, but this time bound to the ***repoDetailsState$**.* This state just has an action passed in, and it will look like:

```typescript
export interface RepoDetailsActions {
    fetchRepoDetails(repo, org): Asap<RepoDetailsData>;
}

export const repoDetailsActionsFn: ActionsFn<RepoDetailsData, RepoDetailsReducers, RepoDetailsActions> = thread => ({
    fetchRepoDetails(repo, org): Asap<RepoDetailsData> {
        return thread.monitor(
            diContext.issuesService.fetchRepoDetails(repo, org).catch(() => thread.reducers.$fetchRepoDetails(-1, "error loading")),
            (repoDetails, reducers) => reducers.$fetchRepoDetails(repoDetails.open_issues_count, ""),
            'fetchRepoDetails',
            [repo, org]
        )
    }
});
```

### Fetching comments

Our last async call will happen when the user selects to open an issue, and we need to show the comments. So the ***issuesCommentsState$***  will have an action that looks like:

```typescript
export interface IssuesCommentsActions {
    fetchComments(issue: Issue): Asap<IssuesCommentsData>;
}

export const issueCommentsActionsFn: ActionsFn<IssuesCommentsData, IssuesCommentsReducersFn, IssuesCommentsActions> = thread => ({
    fetchComments(issue: Issue): Asap<IssuesCommentsData> {
        return thread.monitor(
            diContext.issuesService.fetchComments(issue.comments_url).catch(() => thread.reducers.$fetch([])),
            (comments, reducers) => reducers.$fetchComments(issue.id, comments as IssueComment[]),
            'fetchComments',
            issue.comments_url
        )
    }
})
```

### �Displaying the issues pages

Let's now see how we can display the issues and the repository information. The following fragment belongs to the functional component *IssuesListPage*:

```typescript
<div id="issue-list-page">
    {repoDetailsState$.connectMap<HeaderProps>(
        IssuesPageHeader,
        data => ({
            org: org,
            repo: repo,
            openIssuesCount: data.openIssuesCount
        })
    )
    }
    {diContext.issuesState.connect(IssuesList)}
</div>
```

�It uses connectMap to link **repoDetailsState$** with the component *IssuesPageHeader*, and the DI context to fully connect issuesState with the component *IssuesList*.

### Displaying the comments

The component IssueDetailsPage uses a ConanJs hook [*useConanState*](/data/conan-state/subscribing-state/connecting#hooks) to connect with the state ***issuesCommentsState$*** and retrieve the issues in its own useEffect:

```typescript
const [commentsState] = useConanState<IssuesCommentsData, IssuesCommentsActions>(issuesCommentsState$);

useEffect(() => {
    if (issue) {
        fetchComments(issue)
    }
}, []);

const comments = commentsState.commentsByIssue[issue.id];
let renderedComments;
if (comments) {
    renderedComments = <IssueComments issue={issue} comments={comments}/>
}
```

�

### Getting the code

The full code for this example is available at

{% embed url="<https://github.com/conan-js/conan-js-examples/tree/master/issues-viewer>" %}

or the code sandbox below, for more details on this ConanJs feature.

### Code sandbox

{% embed url="<https://codesandbox.io/s/q9ytd>" %}


# Conan Flow Demos


# Authentication

Try username ***pepito*** and password ***lolito***

or anything else to see it failing auth!

{% embed url="<https://codesandbox.io/s/bhtpu>" %}


# General Concepts

## Conan Data

### **What is it?**

**Conan Data are capsules of data with TACOS.**&#x20;

I know you are curious about the TACOS part, (this is explained below), but first let's look at what data we want to encapsulate:

The key is to encapsulate the necessary logic and business data or meta data that needs to be managed to successfully deliver your requirements.

![](/files/-MCGmSCnpUpejp2QUPNP)

That is quite a mouthful, let's try again with some examples of Conan Data.

* On a web application game, It could be  the current score.
* On an e-commerce application. The current progress for a shopper while on the checkout from a shopping cart.&#x20;
* On a tabs widget. It could be the current tab the user has selected.
* On a CRM application. It could be the list of customers to be displayed on the screen.
* On a timesheet applications. It could be the data and validations behind the form to enter the hours for the week.&#x20;

Something interesting about this type of data, is that is better described not for what it is, but how you usually will want to use it.

And this is where the TACOS part of the description comes into play.

### Attributes (TACOS)

When you develop web applications / components, you are mostly mapping data to a user interface.

We have seen in the previous section how Conan Data lets you put this into capsules, but you will find that  you also need to be able to manage it.

We cover this by providing the following attributes to each Conan Data element that you create.

* **Testable** Testing state e2e is simple
* **Actionable** If you can access the state, you can change it through an action
* **Composable** You can create new state from already existing state easily.
* **Observable** You can observe state and receive updates when the state changes.
* **Scalable** You can have your state global, or you can scope it.

You can use the TACOS as mnemonic to remember the attributes.&#x20;

![T .. A.. C.. O.. S ?!](/files/-MCGs1gCViUmV5zAkjUW)

Have a look at the docs for each the [Conan State](/data/conan-state) and [Conan Flow](/data/flows) to map these attributes to their sections in the documentation.

## Conan State and Conan Flow

There are two flavours of Conan Data, their purpose is the same, to help you encapsulate and manage your application data, but they are better suited for your use case depending on the nature of the data that you want to map.

We like to think that the best way to think about this is to think on how many dimensions would better describe the data that you want to map.

### One dimension - Conan State.

This is likely to be how you are used to think about data.

1D data is data of the same shape that changes over time.

For instance, if you encapsulate the score for a game that you are developing through a Conan State, you can visualize it like this:

| Status       | State 1 | State 2 | State 3 | State 4 |
| ------------ | ------- | ------- | ------- | ------- |
| **nextData** | 0       | 100     | 200     | 300     |

For this use case, Conan State is the best fit to map your data.

### Two dimensions - Conan Flow

There are sone cases where the data is best represented in a matrix, we also think that this is the main use case when working with flows.

Let's think about the authentication flow for instance, first thing that comes to mind, is that a flow has statuses:

notAuthenticated -> authenticating -> authenticated

Then each status will have its one type of data.

For instance, continuing with the authentication example, this could be the types mapped on each status

notAuthenticated -> type: string (reason)\
authenticating -> type: \[username, password]\
authenticated -> credentials

Let's try to represent this visually:

Let's map a user with username 'username' and password 'password' trying to authenticate twice, the first time with the wrong password

| Status               | State 1                                                                                                      | State 2                                                                                                  | State 3                                                                                                   | State 4                                                                                                     | State 5                                                                                           |
| -------------------- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| **notAuthenticated** | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span><br>''                       </p> |                                                                                                          | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span> </p><p>'invalid password'</p> |                                                                                                             |                                                                                                   |
| **authenticating**   |                                                                                                              | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span> </p><p>\[username/TACOS]</p> |                                                                                                           | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span> </p><p>\[username/password]</p> |                                                                                                   |
| **authenticated**    |                                                                                                              |                                                                                                          |                                                                                                           |                                                                                                             | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span></p><p>credentials</p> |

### Statuses & States

If you pay attention to the tables above, even for Conan State, (which is a one dimension data structure) we have Statuses and State.

Conan State is in fact a Flow of one status (nextData).

In summary, in ConanJs all Conan Data has Statuses, and the statuses have states.

**Status:** A stream of states,&#x20;

* **For Conan State**, there is always only one status created for the user, 'nextData' - note that this is transparent to the end user of the Conan State.
* **For Conan Flow**, the user decides how many statuses and their name

**State:** The representation of each data update received in a status.

### Limbo statuses ($init / $stop)

Another cool feature of Conan data, is that you can start / stop it at your own convenience.

Note that for the sake of simplicity we have made both Conan State and Conan Flow to auto start when you create them (unless you explicitly say otherwise )

What this brings to the table, is the ability to help you to work with complex data structures like Streams

{% hint style="danger" %}
Note that as of v1.0 Streams and start / stop are not fully exploited, we would like to create out of the box Streams, add more Docs and Demos to cover for these use cases.

But there is nothing stopping you to explore this functionality on your own
{% endhint %}

This introduces a gap in the Conan Data where while it starts and while it stops is not yet in any status. And that's where the limbo statuses come to play.

**$init:** This is the status the Conan Data stays at while it performs all necessary actions to transition into its first state.

**$stop:** This is the status the Conan Data stays at while it performs all necessary actions to transition out of his last state.

{% hint style="success" %}
Is good to be familiar with these two statuses since you are likely going to see them in your logs, you can listen to them...
{% endhint %}

### Steps & Transitions

At last, now you should be comfortable with the difference between statuses and states.

Steps and transitions are they counterpart methods.

**Steps** Are the methods available to produce a new state for a given status. In the case of the Conan State, these are the [actions](/data/conan-state/actions/types-of-actions).

**Transitions.** Are the methods available to move from a given status to a new status with the provided state, they are explained in the [Conan Flow](/data/flows) section. Note that Conan State does not have a mechanism for transitions as it only has one status.

## Core

Note that ConanJs is agnostic to the UI framework (Angular, Vue, React..), as of v1.0 we provide with classes to use it with React, but we are hoping to add more frameworks soon.

There are 2 pairs of classes that wrap all the logic for the Conan Data.

* **Thread, and Thread Facade.** Wrap all the logic for 1D state.
* **Flow, and Flow Facade.** Wrap all the logic for 2D state.

We have not included detail documentation for this classes, but feel free to explore them if you want to learn the guts of the framework


# Conan State

Conan State are capsules of state that can be reused. To learn more about how to manage data in ConanJs, have a look at our [General Concepts section](/data/general-concepts)

{% hint style="warning" %}
A convention used across the documentation, and that we invite you to use (but is not mandatory) is to suffix your Conan State name with a $. ie todos$
{% endhint %}

**You interact and define your Conan State with reducers and actions**

{% content-ref url="/pages/-M9Z4QHecGnta4vB5w-m" %}
[Actions & Reducers](/data/conan-state/actions)
{% endcontent-ref %}

**If you understand the concepts behind the actions and reducers, then you are ready to see how to create state**

{% content-ref url="/pages/-M9U3wO6w258a6tHMOq5" %}
[Creating State](/data/conan-state/creating-state)
{% endcontent-ref %}

**Subscribing to state will show you how to render your state either by connecting to your own components, or via live rendering**

{% content-ref url="/pages/-M9U5eYpt6BGOrR93K9g" %}
[Observing State](/data/conan-state/subscribing-state)
{% endcontent-ref %}

![Observing state](/files/-MCrCIHSq4xxD2PXrECs)

**With Conan, you can create small Conan State elements which will be easier to test, develop and reuse. Then, you can compose new state based on this atomic states.**

{% content-ref url="/pages/-M9U3yX1qPxyZG1LWazo" %}
[Composing State](/data/conan-state/pipes-composing-state)
{% endcontent-ref %}

**Not all state should be global, or in the context, or local.... With ConanJs you can easily decide how to scope your state**

{% content-ref url="/pages/-M9Z8O0kp8Z\_os\_Ni-RR" %}
[Scaling State](/data/conan-state/scoping-state)
{% endcontent-ref %}

**It is also possible to create interactions between Conan States, for this, you can leverage the reactions**

{% content-ref url="/pages/-MBYUA5WpIuTFb\_RnQx6" %}
[Orchestrating State](/data/conan-state/orchestrating-state)
{% endcontent-ref %}

![](/files/-MBirIq5m9CJNqTpxVjZ)

**Error handling is built-in to make your life easier...**

{% content-ref url="/pages/-MBmrqVj\_VvbyYinkfgC" %}
[Life cycle](/data/conan-state/life-cycle)
{% endcontent-ref %}

**... and so it is managing async use cases ...**

{% content-ref url="/pages/-M9U47JMLJUwzYtw5l00" %}
[Async handling](/data/conan-state/life-cycle/async-handling)
{% endcontent-ref %}

**... and testing is as simple as testing a normal JS object**

{% content-ref url="/pages/-M9U4Da0nvR6lTc3QLb5" %}
[Testing state](/data/conan-state/testing)
{% endcontent-ref %}


# Actions & Reducers

## Introduction

ConanJs allows to interact with the state by using Actions & Reducers.

### Reducers

**Reducers** are used to update the underlying data and must be prefixed with the symbol ‘$’&#x20;

Reducers are not meant to be accessed by users of the State (actions are).

ConanJs will create an action for each reducer automatically.

{% hint style="danger" %}
Always add the $ to your reducer name, if you do so, the framework will create a matching action without the $ (unless you override it)
{% endhint %}

### Actions

**Actions** are automatically created or provided to add additional logic. They serve as interfaces to increase state reusability and are also [chainable](/data/conan-state/actions/types-of-actions#chaining-actions)

{% hint style="success" %}
Actions make up the public API through which your Conan State can be used.
{% endhint %}

### Defaults

Defaults reducers and default actions are always available when a state is created with Conan.

|              | Sync    | Async      |
| ------------ | ------- | ---------- |
| **Reducers** | $update | -          |
| **Actions**  | update  | updateAsap |

Both update and $update can receive either:

* A value to use as new state,&#x20;
* A reducer function to provide a new value based on its current value.

UpdateAsap receives an [ASAP value](/asaps)

{% hint style="info" %}
You can see our '[Hello Wow!](/tutorials/conan-state-demos/hello-wow)' showcasing the usage of the default actions.
{% endhint %}

To learn more about reducers, how to define them, and the default reducer, check out our [reducers section](/data/conan-state/actions/reducers).

To learn more about actions, how to define them, their return value, and the default actions, check out our [actions section](/data/conan-state/actions/reducers).

## Actions as your API&#x20;

Each Conan State will have a clear actions interface which can help to see each ConanState as an injectable capsule of behaviour.

Combined with [Dependency Injection](/dependency-injection) allows developers to think of state as configurable and injected logic.

In your UI you can declare what type of state your component is going to be receiving, and decide its actual implementation.

{% hint style="info" %}
You can see this in our [Todos](/tutorials/conan-state-demos/todos/todos-sync) and [Todos - Async](/tutorials/conan-state-demos/todos/todos-async) examples, where the todo list renderer does not fundamentally change even though one has async actions.
{% endhint %}

### Invoking the actions

Invoking actions is very simple, they are all available under the 'do' property for the state [after it has been created](/data/conan-state/creating-state)

```javascript
myState$.do.myAction
```

![So that we are clear, you can access actions straight from the State!](/files/-MBfZWzxTd8cZv68efi2)

## Guidelines

It might be difficult at first to decide how to shape your Conan State, including its reducers and actions.

To help you decide we provide with the following guidelines.

**1- Create the smallest Conan State that you possibly can.** The best way to do this is to leverage the [light method to create state](/data/conan-state/creating-state#conan-light) and start by not creating any reducers or actions, but just use the out of the box actions **update** and **updateAsap**.\
\
You could have state that represents units of information, like, a list of todos, the current filter to use for an action...\
\
Then, in your views, if you need to combine them, user our [composition patterns](/data/conan-state/pipes-composing-state)\
\
You could also further leverage [our DI](/dependency-injection), to have all these states already prebuilt and injected.

**2- If you need to add more logic, choose creating a reducer first.** Creating [reducers](/data/conan-state/actions/reducers) is simpler than creating [actions](/data/conan-state/actions/types-of-actions), and ConanJs will automatically generate an action for you.

**3- If you need to have a few actions being triggered once after another, of conditionally, see if you can** [**orchestrate them**](/data/conan-state/orchestrating-state) **first.** With ConanJs you can react to changes in a different state

**4- If you need to add async actions, auto-bind them if possible.** Auto binding removes boilerplate code by using a name convention to tie an async operation with its matching reducer.

**5- If you need to add async actions that can't be auto-bind**, **use a monitor action.** Monitors allow you to connect async [Asaps](/asaps) to reducers easily

**6- Create custom actions when you need to add additional logic or override an action.** This is fully explained in the [actions](/data/conan-state/actions/types-of-actions) section


# Reducers

### Introduction

Reducers are functions that update its underlying data synchronously and which name is prefixed with a '$'.

{% hint style="danger" %}
Don't forget to prefix the reducer with a '$' otherwise the framework will not [generate its equivalent action.](/data/conan-state/actions/types-of-actions)

As of v1.0 no error is thrown when declaring a reducer not prefixed with $, but this is likely to change.
{% endhint %}

Reducers are defined when [creating state](/data/conan-state/creating-state) via a function that&#x20;

* Receives a parameterless function that returns the current state at the time of its invocation.

{% hint style="warning" %}
We refer to this parameter as the getData parameter across the docs, we invite you to use the same name on your code
{% endhint %}

* Returns the actual reducers.

Imagine you have state to encapsulate a number, and you want to have two reducers

* $delta: It receives a number and applies it as delta to the current value.
* $multiply: it receives a number to be multiplied to the current value and sets the state to the result.

{% tabs %}
{% tab title="Js" %}

```javascript
getData => ({
    $delta(delta) {
        return getData() + delta;
    },
    $multiply(by) {
        return getData() * by;
    },

})
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
For an example that uses a simple reducer, check our $addTodo reducer in the [Todos](/tutorials/conan-state-demos/todos/todos-sync#creating-the-todos-state) examples
{% endhint %}

### The Reducers Interface

Having the reducers described as a function that receives **getData** and that returns the actual reducers was a meditated decision.&#x20;

We understand that it adds a bit of boilerplate code when creating the state, but it allows the reducers to be described as pure business interfaces.

This, on the long run causes the overall boilerplate code to be less,  as every time you have to use the reducers, you are going to use them through its plain business interface.

{% tabs %}
{% tab title="Js" %}

```javascript
state$.reducers.$delta(2);
state$.reducers.$multiplyBy(3);

```

{% endtab %}
{% endtabs %}

{% hint style="success" %}
This is specially nice if you are using typescript as you can type your Reducers interface.
{% endhint %}

### Default Reducer

Every Conan State has a pre-built reducer. **$update**

One of the key principles of ConanJs is to allow developers creating atomic state, and then [compose it when needed](/data/conan-state/pipes-composing-state).

If you do this, many times you will be able to just use **$update** for most of your use cases&#x20;

**$update** can be invoked in two different ways

* Absolute updates. Passing a simple object, which will be used as the new value.
* Relative updates. Passing a function that receives the current value, and returns the new value based on the value received

{% hint style="success" %}
Relative updates are effectively a neat trick to leat you inline your reducers without having to declare them upfront
{% endhint %}

Imagine you had some Conan State that represents a number, and like the example above, you would like to set/delta/multiply its current value, you could do this easily without having to create the reducers/actions

{% tabs %}
{% tab title="Js" %}

```javascript
//set units bought to 3
unitsBought$.do.update (3)
//increment by one
unitsBought$.do.update (unitsBought=>++unitsBought)
//multiply by
unitsBought$.do.update (unitsBought=>unitsBought * 2)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
For an example that uses a the default actions, check [Hello Wow!](/tutorials/conan-state-demos/hello-wow)
{% endhint %}

### Reducers and Actions

If unspecified, ConanJs will create an action for each reducer that you create, it also provides for the counterpart action **update** associated to the reducer **$update.**

To see details around how can you describe custom actions, or override the actions that ConanJs will create based on your reducers, please check our next section [Actions](/data/conan-state/actions/types-of-actions)


# Actions

### Introduction

Actions build up the API that will shape how to interact with your Conan State.

{% hint style="warning" %}
Actions & Reducers are concepts strongly interlinked with each other, we would strongly recommend to be familiar with the [general concepts](/data/conan-state/actions) as for most use cases you **won't** need to create [custom actions](/data/conan-state/actions/types-of-actions#custom-actions).
{% endhint %}

ConanJs provides automatically with an action for each [reducer](/data/conan-state/actions/reducers), and two out of the box actions **update** and **updateAsap** to deal with sync and async updates (explained in further detail later)

Actions are defined when [creating state](/data/conan-state/creating-state) via a function that

* Receives a [thread](/api/conan-state-classes/thread) to allow you accessing the reducers and other useful resources to describe your actions

{% hint style="info" %}
A Thread is like a Conan State half baked, it has all you need to add additional logic to your actions, like the getData method, the monitor and the reducers already defined. Everything available from a thread is [documented in the API](/api/conan-state-classes/thread)&#x20;
{% endhint %}

* Returns the actual actions.

Imagine that you want to add an async action in your Conan State using the monitor, this could retrieve an authentication token and then you want to set the property of your state authenticated to the response

{% tabs %}
{% tab title="Js" %}

```javascript
thread => ({
    authenticate(authenticationUrl) {
        return thread.monitor(
            Asaps.fetch (authenticationUrl),
            (response, reducers)=> reducers.$update(current=>({
                ...current,
                authenticated: response.authenticated
            }))
        );
    },
})
```

{% endtab %}
{% endtabs %}

Note that this action is handling async operation with the monitor, which is further explained below.

### The Actions Interface

Following the same principles as to the [reducers interface](/data/conan-state/actions/reducers#the-reducers-interface), having the Actions described as a function that takes a thread and returns the actual Actions was also a meditated decision.

The result of this is that you can define a clear business interface that describes the actions that can be performed against your state, so a little bit of boiler plate upfront saves a lot of boilerplate down the line.

You can access all the actions through the 'do' property of your Conan State

```typescript
stockPrices$.do.refresh();
shoppingBasket$.do.addItem(itemToAdd);
```

### Chaining Actions

Another property of an action in ConanJs is that they are chainable, they return an [ASAP](/asaps) of the state this action is going to generate.

Note that this is the case no matter if doing async or sync operations  (as long as you use the monitor or other async techniques, like auto-binding)

This helps solving complex logic, for instance

```typescript
stockOrders$.do.increaseBuyingLimitBy(1000).then(newLimit=>
    stockMarket$.do.getPriceFor('AAPL').then (applPrice=>
        stockOrders$.do.tryToBuy ('AAPL', applPrice / newLimit)
    )
);

```

{% hint style="warning" %}
Typescript users should note that they are likely going to have to create two interfaces one for the Reducers and for the Actions.
{% endhint %}

### �The default actions

Each Conan State alway has two actions:

* **update** For sync updated
* **updateAsap** For async updates

**update** is the counter part of the [default reducer](/data/conan-state/actions/reducers#default-reducer) $update

**updateAsap** uses a monitor and the default reducer $update to let you update the Conan State async

{% hint style="info" %}
For an example that uses a the default actions, check [Hello Wow!](/tutorials/conan-state-demos/hello-wow)
{% endhint %}

### Reducer actions

This are generated automatically by the framework for each reducer, the generated actions will have

* The same name as the reducer but dropping the initial '$'
* Will return an [ASAP](/asaps) of the state that this action will generate

{% hint style="info" %}
For an example that uses reducer actions, check [Todos](/tutorials/conan-state-demos/todos/todos-sync#creating-the-todos-state)
{% endhint %}

### Auto-bind actions

This is the simplest way to generate [asynchronous](/data/conan-state/life-cycle/async-handling) actions, it works by name convention. It will match your provided actions and the already existing reducers following this rules

* It will find you actions which name matches the underlying reducer
* It will assume that the matching provided action returns an ASAP that needs to be resolved for the state to change.
* It will create a monitor on that ASAP and will pass the resulting value to the reducer which this action matches its name into.

{% hint style="info" %}
For an example that uses auto bind, check [Todos - Async](/tutorials/conan-state-demos/todos/todos-async#creating-the-state)
{% endhint %}

### Monitor actions

If auto-bind is not an option, you can use a monitor (monitors are further explained in the [async section](/data/conan-state/life-cycle/async-handling))

{% hint style="info" %}
For an example that uses monitor actions, check [Github issues viewer](/tutorials/conan-state-demos/github-issues-viewer#fetching-the-issues)
{% endhint %}

### Custom actions

You can also create your completely custom actions if none of the previous options work for you.&#x20;


# Creating State

## Introduction

In ConanJs we advocate for splitting the state in its atomic representation and use as much as possible [the default actions](/data/conan-state/actions/types-of-actions#the-default-actions) and to [compose state](/data/conan-state/pipes-composing-state) if you need to combine/derive it.

{% hint style="info" %}
Point to Demo! TBC
{% endhint %}

To help with this, we provide with two main flavours to create state, Conan.light and Conan.state. You can see the details in the [API section for Conan](/api/main-classes/conan)

### Conan.light

Is the simplest way to create state.

Conan.light just receives two parameters:

1. state name: a string used to identify this state
2. the initial value

```typescript
const yetAnotherCounter$ = Conan.light('counter', 0)
```

{% hint style="info" %}
You can see this in our [Hello Wow!](/tutorials/conan-state-demos/hello-wow) demo.
{% endhint %}

### Conan.state

It is the full fledge option to create state, if you have to use this method to create state you will have to pass a StateDef object.

The object is described with detail in its API section [StateDef](/api/main-classes/conan/statedef), but you will likely be interested in passing [Actions & Reducers](/data/conan-state/actions) to it.

**Conan State only with reducers:**

{% tabs %}
{% tab title="Js" %}

```javascript
export const todoListSyncState$ = Conan.state({
    name: 'todos-sync',
    initialData: {
        appliedFilter: VisibilityFilters.SHOW_ALL,
        todos: []
    },
    reducers: getState=>({
        $addTodo: (todo) => ({
            todos: [...getState().todos, todo],
            appliedFilter: getState().appliedFilter
        })
    }),
});
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
You can see how to create a Conan State with reducers in our [Todos](/tutorials/conan-state-demos/todos/todos-sync#creating-the-todos-state) demo.
{% endhint %}

**Conan State with reducers and action:**

```typescript
export const repoDetailsState$: RepoDetailsState = Conan.state<RepoDetailsData>({
    name: 'repo-details',
    initialData: {openIssuesCount: -1, error: null},
    reducers: repoDetailsReducersFn,
    actions: repoDetailsActionsFn
});
```

{% hint style="info" %}
You can see how to create a Conan State with reducers and actions in our [Github](/tutorials/conan-state-demos/github-issues-viewer#creating-the-conan-states) demo.
{% endhint %}

## Guidelines

**1- If possible use Conan.light first.** We recommend to have atomic state, and to [compose state](/data/conan-state/pipes-composing-state) when needed

**2- If you need to create a full fledged ConanState, follow the** [guidelines for creating reducers and actions](/data/conan-state/actions#guidelines)**.** Similar to the previous point, we recommend to simplify the states that you create on your application.

## Demo

{% embed url="<https://codesandbox.io/s/0o579>" %}


# Observing State

## Introduction

Once the ConanState is created, we need mechanisms to add subscribers so that we can display the latest version of the state in the UI.

When deciding how to subscribe to your ConanState, you will have two options.

[**Live Rendering**](/data/conan-state/subscribing-state/live-rendering): Subscribe to the state on the fly on your renderer

[**Connecting**](/data/conan-state/subscribing-state/connecting): Connect your own component as a subscriber.

{% hint style="success" %}
If you come from Redux, you might be more familiar with the Connecting concept, so it might be best to start learning from there.

If you had no previous experience with Redux, we will recommend to check out first our live rendering as it reduces the boiler plate.

Both mechanisms have valid use cases though, so it is good to be familiar with both.
{% endhint %}

## ConanState Context

Every time you subscribe to a new ConanState, that state is stored in the context to simplify access to it down the line.

This means, that if you know that the correct ConanState have been subscribed upstream of the component where you need to use it, then you can retrieve it easily from the context

{% hint style="success" %}
This is very handy to describe widgets that have many sub-renderers where the correct state is  subscribed to at the top level, so all the components down the line can assume that the state is in the context.
{% endhint %}

The context applies to both, **live rendering** and **connecting state.** In their respective sections, you will be able to see the specifics on how to access the context.

{% hint style="info" %}
Contextual state is also a core principle of how to [scope your state](/data/conan-state/scoping-state)
{% endhint %}

## Subscribing options

### Type of connection

There are 4 options to subscribe that we support

* **Direct.** Invoking a connect or a render live method directly from a ConanState instance, this will leverage inlining JS on your render code.
* **HOC.** Similar to direct, but available If you prefer to use a react HOC component as opposed to inline JS
* **Composition.** We have functions that can take your own components and provide a new component where the properties for your component are automatically taken from the ConanState.

{% hint style="success" %}
Redux developers might be familiar with the concept of composition where they have mapStateToProps
{% endhint %}

* **Hooks.** We also have hooks if you prefer to use this approach

### Subscribing to actions?

Every time you subscribe to a ConanState, we also pass the actions, but we only do this for convenience, as mentioned in the Actions & Reducers section, you can [access directly the actions](/data/conan-state/actions#invoking-the-actions) from the ConanState.

We are aware though that for convenience is neat to also receive them when you subscribe to the ConanState, specially if using the context state.&#x20;

### Monitor Info and Meta info

{% hint style="warning" %}
We would recommend getting familiar with the [Conan State life cycle](/data/conan-state/life-cycle) to understand what the Monitor Info and Meta Info are useful for.&#x20;
{% endhint %}

When you subscribe to the data for a Conan State, you might to also want to subscribe to:

* The [Monitor Info](/data/conan-state/life-cycle/async-handling#the-monitor-thread) produced in the Monitor Thread which tracks your async actions
* The Meta Info produced in the Meta Flow which tracks information so that you can introspect what is happening inside the Conan State

{% hint style="success" %}
This would be the case if you wanted to show for instance:

* a loading screen while doing some async action. (Monitor info)
* show a toast if there is an error happening. (Meta info)
  {% endhint %}

In the sections detailing the two main options for connecting: [live rendering](/data/conan-state/subscribing-state/live-rendering) and [connecting](/data/conan-state/subscribing-state/connecting) we also go into detail to explain how to subscribe also to the Monitor Info and the Meta Info

### To map, or not to map

If you need to connect your own component, you might want to map the ConanState to the shape of the props your component receives.

Otherwise, you can create components that receive as props an instance of [ConnectedState](/api/conan-state-classes/connectedstate), if you do so, you will be able to access the data. monitor info, meta info and the actions straight from its properties.

{% hint style="success" %}
In Redux you have to always map state to props, this is because the state is global and you would not want to receive the whole state on your component.&#x20;

In ConanJs the [scope of the state](/data/conan-state/scoping-state) is decided by you, the result of this is that you will likely be able to connect your state without mapping, yet again removing more boiler plate code.
{% endhint %}

## Guidelines

**1- If you need to only access the actions, you don't need to subscribe.** You can access your actions [directly from your state](/data/conan-state/actions#invoking-the-actions)

**2- If you know that the state is in the context, you can just get it from the context.** Check each section for [live rendering](/data/conan-state/subscribing-state/live-rendering) and [connecting](/data/conan-state/subscribing-state/connecting) to see the details

**3- If you can access directly to some atomic state.** It might make sense to just use [direct live rendering](/data/conan-state/subscribing-state/live-rendering#direct)

**4- If you need to adapt an existing component so that now is connected to a ConanState.** Have a look at our [connecting mechanisms](/data/conan-state/subscribing-state/connecting)

## Demo

Please take a look at this code sandbox to see al the subscription approaches working:

{% embed url="<https://codesandbox.io/s/ku1hr>" %}


# Live rendering

Live rendering lets you render your state on the fly on your renderer, no need to have a dedicated component to act as an intermediary.

![Being able to easily render state inlined in your JSX it's pretty neat!](/files/-MBe0lRVTSNBX2fRHEW3)

There are three mechanisms for live rendering.

## Direct

### Data only

You can use the method *connectLive* from the [ConanState](/data/conan-state) object directly.

It takes a renderer function as argument.&#x20;

All you need is to be able to access the ConanState instance.

{% tabs %}
{% tab title="Js" %}

```javascript
{counterState$.connectLive(data => (<h1>{data.counter}</h1>))}

```

{% endtab %}

{% tab title="Ts" %}

```typescript
import {counterState$} from "../../state/counter.state$";


<button onClick={counterState$.do.increment}>Increment!</button>
<button onClick={counterState$.do.decrement}>Decrement!</button>
{counterState$.connectLive(data=>(<div>
                    <h1>{data.counter}</h1>
                    </div>
))}

```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
You can see this in our [Hello Wow!](/tutorials/conan-state-demos/hello-wow) demo.
{% endhint %}

### Data and Monitor Info

{% tabs %}
{% tab title="Js" %}

```javascript

{
    counterState$
        .tuple(counterState$.asyncState)
        .connectLive((data, monitorInfo) => 
            (<h1>{data.counter} - {monitorInfo.status}</h1>)
        )
}

```

{% endtab %}
{% endtabs %}

## HOC

We can also use a High Order Component with live rendering, by using the components *StateLive* and *ContextStateLive:*

{% tabs %}
{% tab title="Js" %}

```javascript
import {ContextStateLive, StateLive} from "conan-js-core";
import { counterState$ } from "../../state/counter.state$";

<StateLive from={counterState$} renderer={(data, actions) => (<div>
                <button onClick={actions.increment}>Increment!</button>
                <button onClick={actions.decrement}>Decrement!</button>
</div>)}/>;
};

<ContextStateLive renderer={data => (<h1>{data.counter}</h1>)}/>

```

{% endtab %}

{% tab title="Ts" %}

```typescript
import {ContextStateLive, StateLive} from "conan-js-core";
import {CounterActions, CounterData, counterState$} from "../../state/counter.state$";

<StateLive<CounterData, CounterActions>
        from={counterState$}
        renderer={(data, actions)=>(
            <div>
                <button onClick={actions.increment}>Increment!</button>
                <button onClick={actions.decrement}>Decrement!</button>
                <CounterDisplay/>
            </div>
        )}
    />

<ContextStateLive <CounterData>
        renderer={data => (
            <h1>{data.counter}</h1>
        )}
/>

```

{% endtab %}
{% endtabs %}

## Composition

Live rendering can also be used with composition. ConanJs provides the functions contextStateLive and stateLive for it:

{% tabs %}
{% tab title="Js" %}

```javascript
import {contextStateLive, stateLive} from "conan-js-core";
import { counterState$ } from "../../state/counter.state$";

stateLive(counterState$, (data, actions) => (<div>
            <button onClick={actions.increment}>Increment!</button>
            <button onClick={actions.decrement}>Decrement!</button>
            <CounterDisplay />
        </div>));
        
contextStateLive(data => (<h1>{data.counter}</h1>))
```

{% endtab %}

{% tab title="Ts" %}

```typescript
import {contextStateLive, stateLive} from "conan-js-core";
import {CounterActions, CounterData, counterState$} from "../../state/counter.state$";

stateLive<CounterData, CounterActions>(
    counterState$,
    (data, actions) => (
        <div>
            <button onClick={actions.increment}>Increment!</button>
            <button onClick={actions.decrement}>Decrement!</button>
            <CounterDisplay/>
        </div>
    )
)

contextStateLive<CounterData>( data => (
    <h1>{data.counter}</h1>
));
```

{% endtab %}
{% endtabs %}

Please take a look at this code sandbox to see al the subscription approaches working:

{% embed url="<https://codesandbox.io/s/2zgr0>" %}


# Connecting

In this section we will explore the three ways available in ConanJs to connect a component with a state. There are four ways of doing it:

## Direct

We can use the Conan state object directly to connect to a component, using the method *connect*. This method will connect the whole state to the specified component&#x20;

{% tabs %}
{% tab title="Js" %}

```javascript
import { counterState$ } from "../../../state/counter.state$";

{counterState$.connect(CounterDisplay)}
```

{% endtab %}
{% endtabs %}

We can also use *connectMap* to connect to specific parts of the state:

{% tabs %}
{% tab title="Js" %}

```javascript
import { counterState$ } from "../../../state/counter.state$";

counterState$.connectMap(CounterContainer, (data, actions) => ({
    decrementCounter: actions.decrement,
    incrementCounter: actions.increment
}));

counterState$.connectMap(CounterDisplay, data => ({
    counter: data.counter
}))


```

{% endtab %}

{% tab title="Ts" %}

```typescript
import {counterState$} from "../../../state/counter.state$";

counterState$.connectMap<CounterContainerProps> (
    CounterContainer,
    (data, actions)=>({
        decrementCounter: actions.decrement,
        incrementCounter: actions.increment
    })
)

counterState$.connectMap<CounterDisplayProps> (
    CounterDisplay,
    data=>({
        counter: data.counter
    })
)
```

{% endtab %}
{% endtabs %}

## HOC

Using the ConanJs component StateConnect, we can connect a React component with a Conan state:

{% tabs %}
{% tab title="Js" %}

```javascript
export const CounterAppHOCAll = () => {
    return <StateConnect from={counterState$} into={CounterContainer}/>;
};
```

{% endtab %}

{% tab title="Ts" %}

```typescript
export const CounterAppHOCAll = (): React.ReactElement => {
    return <StateConnect<CounterData, CounterActions>
        from={counterState$}
        into={CounterContainer}
    />
}
```

{% endtab %}
{% endtabs %}

And then use the state's data and actions within our React component. We can also use Conan's component ContextStateConnect, to achieve the same purpose, connect the whole state with a component:

{% tabs %}
{% tab title="Js" %}

```javascript
<ContextStateConnect into={CounterDisplay}/>
```

{% endtab %}

{% tab title="Ts" %}

```typescript
<ContextStateConnect<CounterData, CounterActions>
    into={CounterDisplay}
/>
```

{% endtab %}
{% endtabs %}

{% hint style="success" %}
Inside the component, we can invoke the actions defined in the state, via props:&#x20;

```typescript
this.props.actions.decrement
```

{% endhint %}

{% hint style="success" %}
We can also access any data property via props:&#x20;

```typescript
<h1>{this.props.data.counter}</h1>
```

{% endhint %}

## Composition

We can also use compositions with the components *contextStateConnect* and *contextStateMapConnect*

*contextStateConnect* will connect the whole state:

{% tabs %}
{% tab title="Js" %}

```javascript
import {stateConnect, contextStateConnect} from "conan-js-core";

stateConnect(counterState$, CounterContainer);

contextStateConnect(CounterDisplay)
```

{% endtab %}

{% tab title="Ts" %}

```typescript
import {ConnectedState, stateConnect, contextStateConnect} from "conan-js-core";

stateConnect<CounterData, CounterActions>(
    counterState$,
    CounterContainer
)

contextStateConnect<CounterData, CounterActions>(CounterDisplay)
```

{% endtab %}
{% endtabs %}

*contextStateMapConnect* will connect only the specified properties:

{% tabs %}
{% tab title="Js" %}

```javascript
import {stateMapConnect, contextStateMapConnect} from "conan-js-core";

stateMapConnect(counterState$, CounterContainer, (data, actions) => ({
    decrementCounter: actions.decrement,
    incrementCounter: actions.increment
}));

contextStateMapConnect(CounterDisplay, (data) => ({
    counter: data.counter
}))
```

{% endtab %}

{% tab title="Ts" %}

```typescript
import {ICallback, contextStateMapConnect, stateMapConnect} from "conan-js-core";
�
stateMapConnect<CounterData, CounterContainerProps, CounterActions>(
    counterState$,
    CounterContainer,
    (data, actions)=>({
        decrementCounter: actions.decrement,
        incrementCounter: actions.increment
    })
)

contextStateMapConnect<CounterData, CounterDisplayProps, CounterActions>(
    CounterDisplay,
    (data)=>({
        counter: data.counter
    })
)
```

{% endtab %}
{% endtabs %}

## Hooks

ConanJs has the hooks *useConanState* and *useContextConanState* to connect to a state:

{% tabs %}
{% tab title="Js" %}

```javascript
import { counterState$ } from "../../../state/counter.state$";
import {useConanState, useContextConanState} from "conan-js-core";

const [, actions, ConanContext] = useConanState(counterState$);
const [data] = useContextConanState();

```

{% endtab %}

{% tab title="Ts" %}

```typescript
import {CounterActions, CounterData, counterState$} from "../../../state/counter.state$";
import {useConanState, useContextConanState} from "conan-js-core";

const [, actions, ConanContext] = useConanState <CounterData, CounterActions>(counterState$);
const [data] = useContextConanState <CounterData, CounterActions>();

```

{% endtab %}
{% endtabs %}

Please take a look at this code sandbox to see al the subscription approaches working:

{% embed url="<https://codesandbox.io/s/2zgr0>" %}


# Composing State

## Introduction

We advocate for creating atomic state and to compose new state when you need to.&#x20;

There are several composition operations that you can perform and that we will see below.

One key aspect of composing state is that it returns another ConanState, which you can compose again.

![Inception!](/files/-MBiEF6H4M2z1c9Hfa_v)

## One state to one state

### Map

We can derive one state into a new one using *ConanState*.*map*:

{% tabs %}
{% tab title="Js" %}

```javascript
productQty$.map((productQty)=>productQty.qty)

productPrice$.map((price)=>price.priceUsd)
```

{% endtab %}
{% endtabs %}

### Filter

We can filter 1 state into a new one using *ConanState.filter:*

```javascript
productQty$.filter((productQty) => productQty.qty % 2 === 0)
    
productQty$.filter((productQty)=>productQty.qty % 2 !== 0)
```

## Two states to one state

### Merge

We can merge 2 states into 1 using *ConanState.merge:*

{% tabs %}
{% tab title="Js" %}

```javascript
productQty$.merge(productPrice$, (productQty, productPrice)
 => productQty && productPrice ? productQty.qty * productPrice.priceUsd : 0)
```

{% endtab %}
{% endtabs %}

### Tuple

{% tabs %}
{% tab title="Js" %}

```javascript
productQty$.tuple(productPrice$)
```

{% endtab %}
{% endtabs %}

## **Many** states to one state

### **Combine**

We can combine N states into a new one using *ConanState.combine*:

{% tabs %}
{% tab title="Js" %}

```javascript
ConanState.combine(`combine`, {
    price: productPrice$,
    qty: productQty$
})
```

{% endtab %}

{% tab title="Ts" %}

```typescript
ConanState.combine<CombinedObject>(
    `combine`,
    {
        price: productPrice$,
        qty: productQty$
    }
)
```

{% endtab %}
{% endtabs %}

�

## Examples

You can navigate these examples in this sandbox:

{% embed url="<https://codesandbox.io/s/0po76?file=/src/app.tsx>" %}
Composing Conan states
{% endembed %}

## Composing State + Dependency Injection

Our dependency injection lets you describe atomic and composed state such that from the point of view of their consumers, they would not know (and won't care) wether if it is atomic state or not.

Check out our [dependency Injection](/dependency-injection) for more details

## Demo

{% embed url="<https://codesandbox.io/s/3zs2m>" %}


# Scaling State

### Introduction

ConanState are normal plain javascript objects. this means that when you decide the scope of your state, you can do it as you would do for any normal object.

On top of that, you can leverage our [application context from the DI](/dependency-injection) to help you scope your state.

In summary, the state of your state can be:

### **Global**&#x20;

You can have global state, mainly you can either import it as a normal object or by leveraging our [application context (DI) ](/dependency-injection)

### **Local**

You can have local state to your component by just declaring it and using it locally to your component&#x20;

### **Context**&#x20;

The moment you connect state, [is stored in the context](/data/conan-state/subscribing-state#conanstate-context), this means that you can use the context state&#x20;

### **Runtime**&#x20;

[By composition](/data/conan-state/pipes-composing-state) you can have state that you use inlined in your JS

### **Component**

You can leverage scoping locally the state at the top of your component renderer and have the renderers down the line leverage the [context state](/data/conan-state/subscribing-state#conanstate-context)

{% hint style="success" %}
There seems to be a trend where you would have to pick not only what tool you would prefer to use to manage your state, but also, that would constraint you on how to scope the state then.

The biggest use case for this, are the libraries that push for state to be always global.

We think that is a mistake, any modern web application has state and being able to choose the adequate scope for it is very important.
{% endhint %}

![](/files/-MBjCOijsAA_mwUi6aPV)


# Orchestrating State

## Introduction

With ConanJs you should be able to write complex interactions easily. There isn't really a single feature that allows for this, but it really is the combination of many of them.

Some of them we have already seen:

* [Invoking actions](/data/conan-state/actions#invoking-the-actions) directly from the state
* [Chaining actions](/data/conan-state/actions/types-of-actions#chaining-actions). All actions in ConanJs return an [ASAP](/asaps), so you can guarantee that you can execute logic immediately after the actions is completed.
* [Composition](/data/conan-state/pipes-composing-state). Complex use cases many times requires composing actions like, filter, map...
* [Scoping](/data/conan-state/scoping-state). Being able to isolate state to operate on it will also help with complex logic.

But there is a key feature that we have not explored yet, Reactions.

You can add reactions to your ConanState by calling [addDataReaction](/data/conan-state). The principle of this very simple, you provide with some logic that will be executed every time the state changes.

## Complex scenario

![Generate alerts based on buy/sell orders and the stock prices](/files/-MBirIq5m9CJNqTpxVjZ)

### Initial atomic state

These example starts with four atomic states.

```typescript
const stock$ = Conan.light<StockPrice[]>('stock', [{
    id: 'TSLA',
    price: 1000
},{
    id: 'AAPL',
    price: 350
}]);

const stockOrder$ = Conan.light<StockOrder[]>('stockOrders', [{
    stockId: 'AAPL',
    buy: 300,
    sell: 400
},{
    stockId: 'TSLA',
    buy: 900,
    sell: 1200
}]);

const alertsByStock$ = Conan.light<IKeyValuePairs<StockAlert[]>>('alerts', {});

const alertStream$ = alertsByStock$.map<StockAlert[]>(alertsByStock => {
    let newStream: StockAlert[] = [];
    Objects.foreachEntry(alertsByStock, (stockAlerts)=>newStream = [...newStream, ...stockAlerts])
    return newStream.sort((left, right)=>left.timestamp - right.timestamp);
});
```

**stock$** has the code and price for each stock

**stockOrder$** has the buy and sell orders that will trigger alarms

**alertsByStock$** the list of alerts by stock key based on stock$ and stockOrder$

**alertStream$** as we want to show a list of alerts, we use this derived state to build the list of states based on alertsByStock$ (this is explained further below)

### Generating the alerts

Alerts are generated based on any change in either the **stock$** or the **stockOrder$,** below you can see the logic for this.

```typescript
stockOrder$.tuple(stock$).addDataReaction({
    name: `checking alerts`,
    dataConsumer: ([stockOrders, stocks]) => {
        let newAlerts: StockAlert[] = [];
        stockOrders.forEach(stockOrder => {
            const stock = stocks.find(it => it.id === stockOrder.stockId);
            let operation: 'buy' | 'sell' | 'keep';
            if (stock.price >= stockOrder.sell) {
                operation = 'sell';
            } else if (stock.price <= stockOrder.buy) {
                operation = 'buy';
            } else {
                operation = 'keep';
            }
            newAlerts.push({
                operation,
                orderSnapshot: stockOrder,
                stockSnapshot: stock,
                timestamp: Date.now()
            })
        });

        let nextState: IKeyValuePairs<StockAlert[]> = {...alertsByStock$.getData()};
        newAlerts.forEach(newAlert => {
            if (nextState[newAlert.stockSnapshot.id] == null) {
                nextState[newAlert.stockSnapshot.id] = [newAlert];
            } else {
                let alertsForStock: StockAlert[] = nextState[newAlert.stockSnapshot.id];
                let lastAlert = alertsForStock[alertsForStock.length - 1];
                if (
                    !Objects.deepEquals(newAlert.stockSnapshot, lastAlert.stockSnapshot) ||
                    !Objects.deepEquals(newAlert.orderSnapshot, lastAlert.orderSnapshot)
                ) {
                    alertsForStock.push(newAlert);
                }
            }
        })

        alertsByStock$.do.update(nextState);
    }
})
```

#### �Merging two states with a tuple:

At the top we [merge with a tuple](/data/conan-state/pipes-composing-state#tuple) the stock orders, and the stock, this generate a new ConanState that will contain an array of two elements, the stock orders and the stock prices, if any of them changes, a new state will be created.

```typescript
[...] stockOrder$.tuple(stock$) [...]
```

#### Adding a reaction:

Immediately after, we add a reaction to the tuple

```typescript
[...] .addDataReaction({
    name: `checking alerts`,
    dataConsumer: ([stockOrders, stocks])=> {
    [....]
    }
})
```

#### Invoking an action:

Note that the bulk of the logic is to decide if based on the new price and order information a new alert to keep / buy or sell should be generated.

The alerts are built on the back of the reaction into:

```typescript
let nextState: IKeyValuePairs<StockAlert[]>
```

The alerts are a map of stock code to any the list of alerts they have.

Once this object is built, all we need to do is to update the alerts state.

```
alertsByStock$.do.update(nextState);
```

### Streaming the alerts

As mentioned at the beginning we ultimately want to see a stream of alerts on the screen.

Note how we easily manage to do this by composing a new state via map from **alertsByStock$**

```typescript
const alertStream$ = alertsByStock$.map<StockAlert[]>(alertsByStock => {
    let newStream: StockAlert[] = [];
    Objects.foreachEntry(alertsByStock, (stockAlerts)=>newStream = [...newStream, ...stockAlerts])
    return newStream.sort((left, right)=>left.timestamp - right.timestamp);
});
```

![](/files/-MBioncopFrP0Vne6d48)

## See the code by yourself

You can see this in action here:

{% embed url="<https://codesandbox.io/s/github/conan-js/conan-js-examples/tree/master/orchestratingState>" %}


# Life cycle

## Introduction

Each ConanJs state object has a a life cycle. This life cycle helps tracking several aspects of the State including:

* [Monitor async operations](/data/conan-state/life-cycle/async-handling)
* [Provide with introspection](/data/conan-state/life-cycle/introspection)&#x20;

To understand the life cycle we need to get some insight on what is inside a ConanState. It is composed of.

* The Main Thread
* The Monitor Thread (for async operations)
* The Meta Flow (for introspection / error handling)

We also need to introduce the thread and flows

## Threads and Flows

Threads and flows are the building blocks of ConanJs, while you don't need to have a deep understanding of them, it is helpful to have an overview.

### Threads

Threads are streams of data that have the same shape.

When you update the state of the Conan State through an [action](/data/conan-state/actions), the main thread is notified and stores the new state, so it can be accessed.

### Flows

Flows have statuses, each status then has, similar to the thread, a stream of data with the same shape.

A flow has a current status, and you can also transition to a different status.

Note that flows are not exactly the same as [Conan Flows](/data/flows), but they are very similar.

Both threads and flow can be [started or stopped](broken://pages/-MBmtP5NHJQKJIXkc0rZ)

{% hint style="success" %}
ConanJs auto-starts Conan State for you, so most of the times you don't have to worry about this.

Is a handy feature to have though for advanced use cases
{% endhint %}

## The Main Thread

The main thread is where all the data updates are stored.

Most of the features of the Conan State affect this Thread, it is also not accessible directly to protect it from unintentional changes.

## The Monitor Thread

The monitor thread collects all the information around async operations, and models that information into  [MonitorInfo](/api/conan-state-classes/monitorinfo) objects.

Check the [async handling](/data/conan-state/life-cycle/async-handling) section for more information on how to use this thread.

## The Meta Flow

The meta flow has the several statuses that are handy to provide with introspection.

It maps all the information into [MetaInfo](/api/conan-state-classes/metainfo) objects

Check the [Introspection](/data/conan-state/life-cycle/introspection) section for more information.

## Accessing the Monitor Thread and the Meta Flow&#x20;

Each ConanState allows easy access to the information encapsulated in the monitor flow and the meta flow through.... (can you guess it?).... more ConanState!

![Recursion!](/files/-MBsO5MnIfLQgalznpQN)

There are two properties in the ConanState for this

* **asyncState.** Returns a ConanState representation of the [Monitor Info](/api/conan-state-classes/metainfo) contained in the Monitor Thread. Since it returns a new ConanState, you can perform all the operations that you would with any other ConanState!
* **metaFlow.** Returns a [ConanFlow](/data/flows) which in turn, it can also be decomposed to obtain different ConanState

### Accessing only one state at a time

You could subscribe to the state produced by these properties as you would with any normal Conan State/ Conan Flow, this will work well if you want to consume in isolation the Meta info or the Monitor Info.

{% hint style="success" %}
This could be the case when you have a loading overlay component where you are only interested in showing if some state is currently performing an asyncAction.

You could [subscribe to](/data/conan-state/subscribing-state):

myState$.asyncState
{% endhint %}

Many times though you are probably going to be interested in combining the data with either the Meta info and/or the Monitor info.

In that case you have two options.

Do this yourself by composing a new state using the original ConanState and the results from the properties asyncState/metaFlow, and subscribe to this new state.

Leverage the ability to subscribe not only to data but a[ combination of data / monitor info / meta info.](/data/conan-state/subscribing-state#monitor-info-and-meta-info)&#x20;

{% content-ref url="/pages/-M9U47JMLJUwzYtw5l00" %}
[Async handling](/data/conan-state/life-cycle/async-handling)
{% endcontent-ref %}

{% content-ref url="/pages/-MBmsuicPsAxBh9nAJ\_y" %}
[Introspection](/data/conan-state/life-cycle/introspection)
{% endcontent-ref %}


# Async handling

## Introduction

ConanJs gives you a few mechanisms to announce within your actions that you are performing asynchronous operations.

These are the benefits:

* **NO boiler plate code to update your state asynchronously**.
* **Automatically updates the** [**Monitor Thread**](/data/conan-state/life-cycle#the-monitor-thread) **to reflect all the async operations running and their details.** Allowing you to subscribe to these updates, to easily add loading screens, block buttons etc.

{% hint style="info" %}
Check our [Todos - Async](/tutorials/conan-state-demos/todos/todos-async) for an example without boiler plate code and which displays the status of the async operations
{% endhint %}

* **Allows accessing the underlying** [**ASAPs**](/asaps) **running at the moment.** Note this combined with the ASAPs being cancellable, makes complex scenarios like optimistic updates much simpler

{% hint style="info" %}
Check our [Todos - Optimistic](/tutorials/conan-state-demos/todos/todos-optimistic) for an example with optimistic updates
{% endhint %}

## Async Actions

There are two mechanisms to declare async actions: auto-bind and monitor actions.

### Monitor actions

[When you describe your actions](/data/conan-state/actions/types-of-actions), you can access the monitor from the provided thread and the framework will update the [Monitor Async thread](/data/conan-state/life-cycle#the-monitor-thread) all the way through the life cycle of the ASAP

```typescript
return thread.monitor(
    //An Asap
    diContext.issuesService.fetch(repo, org, page).catch(() => thread.reducers.$fetch([])),
    //What to do when the asap resolves
    (issues, reducers) => reducers.$fetch(issues as Issue[]),
    //Next two params are for logging purposes
    // - Description of the async operation
    'fetch',
    // - Payload (also shown on the logging)
    [repo, org, page]
)
```

{% hint style="info" %}
Check our [Github](/tutorials/conan-state-demos/github-issues-viewer) example to see a monitor example.
{% endhint %}

### �Auto-bind

Auto-bind works based on naming convention, it basically builds a monitor automatically for a given reducer given a method that returns an ASAP.

The requirements for autoBind are.

* The reducer and the action to auto-bind should have matching names (reducer prefixed with a $, action without it)
* They reducer must take only one parameter.
* The action to autobind needs to return an ASAP of the same type as the type from reducer parameter.

If all these requirements are met, the action you passed through the autobind will be now accessible as an action for the ConanState and, if you invoke it, in addition to returning the ASAP it will monitor it and invoke the associated reducer.

This is better seen with an example

```typescript
function updateToAsync (): ASAP<number>{ 
    //This could be any ASAP, in this case we use a dummy delay
    return Asaps.delay (3, 1000);
}

const autoBoundCounter$ = Conan.state ({
    name: 'autoBoundCounter',
    reducers: getState => ({
        $updateTo (newValue) {
            return newValue
        }
    }),
    autoBind: {
        updateTo: updateToAsync
    }
})

// This will update to 5 in 1s
autoBoundCounter$.do.updateTo (5)

```

{% hint style="info" %}
You can also see this using a service in this example [Todos - Async](/tutorials/conan-state-demos/todos/todos-async)
{% endhint %}

## The Monitor Thread

The monitor thread contains the updates to the Monitor Info caused by changes in async actions.&#x20;

The value of the [Monitor Info](/api/conan-state-classes/monitorinfo) when there are no async actions running is:

```typescript
{
    inProgressActions: [],
    status: MonitorStatus.IDLE, //'IDLE'
}
```

This state is reached as soon as you start the Conan State, or as soon as all the async actions running are fulfilled.

There are three properties in the monitorInfo

* currentAction: This will be populated if there is at least one async action running at the moment, this will contain the representation of the async action that is right now causing an update in the Monitor Thread.
* status: One of the following

```typescript
export enum MonitorStatus {
    IDLE = 'IDLE',
    ASYNC_START = "ASYNC_START",
    ASYNC_FULFILLED = "ASYNC_FULFILLED",
    ASYNC_CANCELLED = "ASYNC_CANCELLED",
}
```

* inProgressActions: All the actions running at the time that this currentAction is being updated.

### Example

A new monitor actions is triggered with name 'updateAsync' and its payload is '5' the Monitor Info would update immediately to:

```typescript
{
    inProgressActions: [{
        name: 'updateAsync',
        payload: 5,
        asap: [theAsap]
    }],
    currentAction: {
        name: 'updateAsync',
        payload: 5,
        asap: [theAsap]
    },
    status: MonitorStatus.ASYNC_START, //'"ASYNC_START"'
}
```

If another action is triggered, with the same name, but with a payload of '3', the monitor info would look like:

```typescript
{
    inProgressActions: [{
        name: 'updateAsync',
        payload: 5,
        asap: [theAsap]
    },{
        name: 'updateAsync',
        payload: 3,
        asap: [theAsap]
    }],
    currentAction: {
        name: 'updateAsync',
        payload: 3,
        asap: [theAsap]
    },
    status: MonitorStatus.ASYNC_START, //'"ASYNC_START"'
}
```

If the action with payload 3 is resolved successfully:

```typescript
{
    inProgressActions: [{
        name: 'updateAsync',
        payload: 5,
        asap: [theAsap]
    }],
    currentAction: {
        name: 'updateAsync',
        payload: 3,
        asap: [theAsap]
    },
    status: MonitorStatus.ASYNC_FULFILLED, //'ASYNC_FULFILLED'
}
```

Then, if the action with payload 5 is resolved, since is the last one, the Monitor Info will update twice.

Once so that we know that the async action has been fulfilled

```typescript
{
    inProgressActions: [{
        name: 'updateAsync',
        payload: 5,
        asap: [theAsap]
    }],
    currentAction: {
        name: 'updateAsync',
        payload: 5,
        asap: [theAsap]
    },
    status: MonitorStatus.ASYNC_FULFILLED, //'ASYNC_FULFILLED'
}
```

Once more to let us know that no more async actions are running at the moment

```typescript
{
    inProgressActions: [],
    status: MonitorStatus.IDLE, //'IDLE'
}
```


# Introspection

## Introduction

ConanJs gives you the ability to check on its internal status so that you can leverage this information for common use cases. For instance:

* You can check if there has been an error and [handle it anyway you prefer](broken://pages/-M9U43o_b-Vt7S9to1yk).
* You can check if there are operations running at the moment, and wait for them to finish, [very handy for testing](/data/conan-state/testing).
* You can also test for the state to be [stopped / started](broken://pages/-MBmtP5NHJQKJIXkc0rZ) so you can react accordingly.

## The Meta Flow Statuses

These are the different statuses in the meta flow:

* **starting**. The Conan State is starting
* **init**. The Conan State has started and reached the first initial state.
* **running**. The Conan State is running at least one action (sync or async)
* **idle.** The Conan State is started but is not running anything at the moment.
* **idleOnTransaction.** Similar, but on a transaction, while on a transaction, the idle status only is reached when the transaction is closed. This is very handy for [testing](/data/conan-state/testing)
* **error** An error has occurred

## The MetaInfo

The information for each status is encapsulated in a [MetaInfo](/api/conan-state-classes/metainfo) object, which has three properties:

* **lastError**: The last error raised
* **transactionCount:** The count of transactions opened at the moment.
* **status:** One of

```typescript
export enum MetaStatus {
    STARTING = 'STARTING',
    INIT = "INIT",
    RUNNING = "RUNNING",
    ERROR = "ERROR",
    IDLE = "IDLE",
    IDLE_ON_TRANSACTION = "IDLE_ON_TRANSACTION",
}
```

## Transactions

Is possible to open a transaction for a [ConanState](/api/main-classes/conan-state)

```typescript
numberValue$.openTransaction(`test-transaction`)
```

�When you open a transaction, the IDLE state will only be reached if all actions (sync and async) are fulfilled and the transaction is closed

```typescript
numberValue$.closeTransaction()
```

{% hint style="success" %}
As of v1.0 transactions don't really honour their name, ie, they only let you group actions to know when they complete, which we think is very useful for [testing](/data/conan-state/testing)

In future releases we are hoping for transactions to be much powerful and let you perform operations like rollbacks / commits...

Stay tuned!
{% endhint %}

![Working hard on the next version!](/files/-MC6e2LYVlVH5tpWHUFc)

## Accessing the Meta Flow

In every [Conan State](/data/conan-state), you have a property to retrieve the meta Flow

```typescript
numberValue$.metaFlow
```

You can check our [Conan Flows](/data/flows) docs to see how you can normally access the different statuses.

We do have dedicated sections for [error handling](broken://pages/-M9U43o_b-Vt7S9to1yk) and [testing state](/data/conan-state/testing) which are heavily connected to the Meta Flow

### Stop / Start

ConanState objects can be *stopped* and *started* on demand. At the moment they always start up *started*.

{% hint style="success" %}
Stopping / Starting Conan State can be useful if you need to work with streams of data or other similar use cases.

At the moment this is not something that you are going to fully leverage as our APIs need to be matured.
{% endhint %}

### Error Handling

A particular use case to access the meta flow is to handle errors, every time an exception is thrown in your code, it is caught and the monitor is updated to reflect this.

This is handy if you want to then add a toast message or something similar.

{% hint style="success" %}
We see error handling to be associated with the transactions, as mentioned above, this is something where we are expecting to provide with more features in the next releases/
{% endhint %}


# Testing state

## Introduction

ConanJs makes testing end to end state simple.

This is because of some principles.

* We use internally [ASAPs](/asaps), which work like a promises except that, if possible, they will run the promised code sequentially (only code that needs to be deferred will be deferred, like fetching data).
* We provide with mechanisms to [handle async actions](/data/conan-state/life-cycle/async-handling) out of the box
* We provide with [introspection](/data/conan-state/life-cycle/introspection) so you can check if there is any operation running at the moment (even asynchronous ones)

That all together makes it so that you can have two main guarantees:

* You will always be able to read the latest state from ConanState
* You can easily execute actions and predict and react when they are settled so you can write your expectations

To showcase the features available for testing and to stay aways from picking a testing framework, we have put together an example that we will breakdown below

## Testing simple actions

### Sync Actions

<div align="left"><img src="/files/-MC7YMIa4waZY9Nx-nqH" alt=""></div>

To test for synchronous values there isn't anything special to do, as soon as the execution of the action is completed, the new state can be already be checked.

```typescript
numberValue$.do.update(3);
//at this point the value of the state is 3
console.log(numberValue$.getData())
//this will print 3
```

### Async Actions

<div align="left"><img src="/files/-MC7Yw6UbRvAY_gwVbFa" alt=""></div>

To test for a single asynchronous action, the best approach is to [chain the action](/data/conan-state/actions/types-of-actions#chaining-actions) with the actual test:

```typescript
numberValue$.do.updateAsap(Asaps.delayed(3, 1000)).then ( ()=>{
    //at this point the value of the state is 3
    console.log(numberValue$.getData())
    //this will print 3
})

```

## Testing event list

<div align="left"><img src="/files/-MC7dVs4iRn1sTS2pwEh" alt="We can query all the values that the ConanState has been updated to"></div>

No matter how many operations you perform in your Conan State, all the state changes are stored for you to query,

This is handy if you are not so interested in the last state, but in the sequence of states. You can see the details for [getEvents() on the ConanState API page](/api/main-classes/conan-state)

For instance to get all the states as an array in the example in this page we use:

```typescript
numberValue$.getEvents().serialize({
    eventTypes: [StatusEventType.STATE],
    excludeInit: true,
})
    .map((it: StateEvent, i) => it.data != null ? it.data : '[undefined]')
    .join(', ')
```

## Testing using introspection

The ability to [introspect](/data/conan-state/life-cycle/introspection) the actual status of the Conan State can prove very helpful when testing complex actions.

### Async actions without transactions

![](/files/-MC7iTVjdSDy1tk7wgJO)

The first use case where this can be very handy is when it comes to waiting for a few async actions to complete.

As you can see, if you have overlapping async actions, you can just run them all together, and wait for the idle status which will be triggered as soon all of them all resolved.

### Any action with transactions

![](/files/-MC7mH1UcK9NYvaXNpEX)

For more complex cases, or when you want to bundle synchronous actions, you can leverage transactions.

If you open a transaction, the Conan State machine would not reach IDLE until the transaction should be IDLE AND the transaction is closed.

This could be useful if you are not sure of the nature of the timing of the actions that you are testing. In these cases, you could open a transaction, launch all of your actions, and then, close the transaction and listen for the next IDLE.

![The feeling when you can easily test E2E your state](/files/-MC7XB6moMvZ-c_us9hN)

## Demo

{% embed url="<https://codesandbox.io/s/f7t2c>" %}


# Conan Flow

{% hint style="success" %}
As of v1.0 Conan Flows are in they early inception, they are fully functional, but in future releases we will be looking to:

* Make them easier to create.
* Allow them to be easier/have more options to subscribe to.
* Add more features on top of them
  {% endhint %}

To see how to create flows...

{% content-ref url="/pages/-M9U7XCo-dXPV6CR9lR\_" %}
[Creating Flows](/data/flows/creating-flows)
{% endcontent-ref %}

To see how to use flows...

{% content-ref url="/pages/-M9U7cLgvlKmRZ\_5X\_O4" %}
[Serialising Flows](/data/flows/flows-as-state)
{% endcontent-ref %}

To see how apart from serialising, you can also observe flows...

{% content-ref url="/pages/-MCGyBaveah67TW2aqPr" %}
[Observing Flows](/data/flows/testing-flows)
{% endcontent-ref %}


# Creating Flows

## Introduction

You can create a [Conan Flow](/api/main-classes/conanflow) object, by using the method [Conan.flow](/api/main-classes/conan) which takes a [UserFlowDef](/api/main-classes/conanflow/userflowdef).

In summary a UserFlowDef receives:

* name: The name of the flow.
* statuses: A JS object where each key represents the name of the status, and each value represents the status definition ([UserStatusDef](/api/main-classes/conanflow/userflowstatusesdef)). In the status definition we can optionally specify any of these properties:
  * Reactions. An array of callbacks to execute as soon as this status is reached.
  * Transitions: The available functions that can be executed while the Flow is on this status and that will cause the flow to move to a different status (Transitions and is explained below in detail). **Note that you always can transition to a different status using the default transition $toStatus.**
  * Steps.The available functions that can be executed while the Flow is on this status and that will cause the flow to move to a different state (this is explained below in detail)

```typescript
Conan.flow({
    name: 'authentication',
    statuses: {
        notAuthenticated: {},
        authenticated: {},
        authenticating: {
            reactions: [
                onAuthenticating => {
                    let valid = DummyAuthenticator.authenticate(onAuthenticating.getData()[1]);
                    const nextStatus = valid ? {
                        name: "authenticated" as any,
                        data: "TOKEN"
                    } : {name: "authenticationFailed"};
                    setTimeout(() => onAuthenticating.do.$toStatus(nextStatus), 2000);
                }
            ],
        },
        authenticationFailed: {
            reactions: [
                onAuthenticationFailed => setTimeout(() => onAuthenticationFailed.do.$toStatus("notAuthenticated"), 2000)
            ],
        }
    },
    initialStatus: {
        name: 'notAuthenticated',
    }
})
```

{% hint style="info" %}
You can see this in our [Authentication demo](/tutorials/conan-flow-demos/authentication)
{% endhint %}

## Statuses

### Definition

{% hint style="success" %}
We would recommend reading about the [general concepts](/data/general-concepts)  for Conan Data before deep diving into understanding the statuses for a flow.
{% endhint %}

The key element for a flow is the statuses that define**s** it. In the case of the example for the authentication flow, the statuses are:

**notAuthenticated, authenticated, authenticating**, **authenticationFailed**

The initial status (the status the flow starts with after it has been created is)

**notAuthenticated**

### **Reactions / Steps / Transitions**

Each status can also receive:

* **Reactions**: Logic to execute every time a new state is provided on this status.
* **Steps**. The available methods to generate new states for this status
* **Transitions**. The available methods to transition to different status from this status.

To define all the statuses, you need to provide a key value pair to the [UserFlowDef.statuses](/api/main-classes/conanflow/userflowdef) property where each key is the name of the status.

You can also decide to only pass an empty object as the configuration for the status, when you do this, the status will be created with no reactions/steps or transitions.

This is the case in the example for the statuses: **notAuthenticated** and **authenticated.**

### **Initial Status**

A flow also has an initial status.

You need to specify two things for the initial status:

* **name**: \[mandatory] It should match the name of one of the defined statuses
* **data**: \[optional] The initial state for that status.

{% hint style="success" %}
To see how to use Conan Flows after they have been created, check our next section to see how to [serialise them into different Conan States](/data/flows/flows-as-state).
{% endhint %}


# Serialising Flows

## Introduction

Before introducing flow serialising,  is important to remind that Conan Flows are [2 dimensional data structures](/data/general-concepts#two-dimensions-conan-flow).

We believe that for most use cases, when you would like to access a flow you would like to serialise it.

Let's illustrate this graphically. Let's use again the authentication example:

| Status               | State 1                                                                                                      | State 2                                                                                                  | State 3                                                                                                   | State 4                                                                                                     | State 5                                                                                           |
| -------------------- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| **notAuthenticated** | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span><br>''                       </p> |                                                                                                          | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span> </p><p>'invalid password'</p> |                                                                                                             |                                                                                                   |
| **authenticating**   |                                                                                                              | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span> </p><p>\[username/TACOS]</p> |                                                                                                           | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span> </p><p>\[username/password]</p> |                                                                                                   |
| **authenticated**    |                                                                                                              |                                                                                                          |                                                                                                           |                                                                                                             | <p><span data-gb-custom-inline data-tag="emoji" data-code="1f4a1">💡</span></p><p>credentials</p> |

We provide you with two serialisation mechanisms, one to serialise everything, the other one to serialise a single status.

Both of them leverage Conan State to provide you the final serialised result.

### toStateAll() - Serialising everything

```typescript
authentication$F.toStateAll()
```

By serialising all, you will create a [ConanState](/api/main-classes/conan-state) of [Status](/api/main-classes/conanflow/status)

From the example above, this would be the visual equivalent of the generate ConanState.

|              | State 1                                                                                                                    | State 2                                                                                          | State 3                                                                                          | State 4                                                                                             | State 5                                                                                  |
| ------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| **nextData** | <p><strong>name</strong><br>notAuthenticated</p><p><strong>data</strong><br><strong>''</strong>                       </p> | <p><strong>name</strong><br>authenticating</p><p><strong>data</strong><br>username/<br>TACOS</p> | <p><strong>name</strong><br>notAuthenticated</p><p><strong>data</strong><br>'invalid pass..'</p> | <p><strong>name</strong><br>authenticating</p><p><strong>data</strong><br>username/<br>password</p> | <p><strong>name</strong><br>authenticated</p><p><strong>data</strong><br>credentials</p> |

### �toState(statusName) - Serialising a single status

Similar to toStateAll, toState statusName), will generate a ConanState of the data type associated to the status being serialised.

Let's have a look at a couple of examples

```typescript
authentication$F.toState('notAuhtenticated')
```

Will generate a ConanState which will provide the following states

|              | State 1 | State 2            |
| ------------ | ------- | ------------------ |
| **nextData** | **''**  | 'invalid password' |

```typescript
authentication$F.toState('authenticating')
```

Will generate a ConanState which will provide the following states

|              | State 1           | State 2              |
| ------------ | ----------------- | -------------------- |
| **nextData** | \[username/TACOS] | \[username/password] |

{% hint style="info" %}
To see some example for serialisation, check our [Testing State](/data/conan-state/testing), in that example, we leverage the serialisation of flows to show what the underlying [meta flow](/data/conan-state/life-cycle#the-meta-flow) is doing
{% endhint %}

## Using Conan Flows

You might be familiar with the [TACOS](/data/general-concepts#attributes-tacos) acronym that describe the attributes for Conan Data.

[Conan State](/data/conan-state) documents these in detail in its different document sections.

By being able to transform Conan Flows into Conan State, you should be able to leverage these attributes for Conan Flows too.

Note that for convenience we also provide with some shortcuts for [observing flows](/data/flows/testing-flows), but we think the best way to leverage flows is to convert them into Conan State.


# Observing Flows

## Introduction

As described on the [serialising flows](/data/flows/flows-as-state), you should be able to serialise a Flow to a ConanState that suits you, and then leverage all the features of the [Conan State](/data/conan-state) to observe it.

We have though some mechanisms to provide you with a shortcut when observing flows

{% hint style="danger" %}
As of v1.0 we only have hooks, but we are planning to add more shortcuts to observe directly flows without having to serialise them
{% endhint %}

## Hooks

### useFlow

```typescript
useFlow<AuthenticationState,AuthenticationFlow>(
        authentication$F, 
        setState, 
        (status, previousState) => ({
                ...previousState,
                current: status.name,
        })
);
```

This hook receives&#x20;

* a flow
* the method to set the state for this component
* a function that returns the new state and that takes
  * the status information that has just been updated
  * the previous state

### useFlowStatus

```typescript
useFlowStatus<AuthenticationState, AuthenticationFlow,"authenticating">(
        authentication$F, 
        "authenticating", 
        setState, 
        (status, previousState) => ({
                ...previousState,
                currentUser: status[0]
         }
 ));
```

This hook receives&#x20;

* a flow
* the name of the status to subscribe to
* the method to set the state for this component
* a function that returns the new state and that takes
  * the state information that has just been updated
  * the previous state

{% hint style="info" %}
To see an example of hooks, check our demo [Authentication](/tutorials/conan-flow-demos/authentication)
{% endhint %}


# Dependency Injection


# General Concepts

## Introduction

Dependency injection is a common technique in software development.&#x20;

If you are not familiar with it, and you are curious about technical details,  you might find more information on this wiki page:

{% embed url="<https://en.wikipedia.org/wiki/Dependency_injection>" %}

With dependency injection, you get to delegate the responsibility of creating the objects that encapsulate the logic of your system, basically ConanJs will create the objects for you, the objects created this way are called **beans**

{% hint style="success" %}
Dependency Injection is a bit like testing, if you are new to it and have never tried it, it will look intimidatory and unnecessary.

But similar to testing, once that you try it and understand it, there is no turning back.

If this is your first contact with dependency injection, we would suggest to head first to [Creating the context](/dependency-injection/creating-the-context) to get some hands on perspective.
{% endhint %}

In summary:

* You will describe what objects you want to create through **bean definitions**
* You will pass a key value pairs of **bean names** to **bean definitions** to the **ContextFactory**
* The context factory will **resolve by name** the objects to be created according to your **bean definitions** and create the **beans**
* Finally the **beans** will be accessible through the **context**.

Let's have a look at each of these terms

## The Beans

A bean is a plain JS object that is resolved on the back of the bean definitions that you provide to the [**DiContextFactory.createContext**](/api/dependency-injection/dicontextfactory).

In other words, **the bean is the final object that ConanJs creates for you and that it will be available from the context.**&#x20;

{% hint style="success" %}
The name bean is taken from the [Java World](https://www.baeldung.com/spring-bean).&#x20;

Some people will argue that we named it like this so we could say that this is the first framework ever with [TACOS](/data/general-concepts#attributes-tacos) and BEANS... they might be right.
{% endhint %}

![A rare capture of ConanJs providing Beans through the context](/files/-MCQpEudbPXNQjDkuw6X)

## The context

The Context is a plain object that contains the beans.

The context is created through the [**DiContextFactory.createContext**](/api/dependency-injection/dicontextfactory)**,** this method receives the key value pairs of **bean names** to **bean definitions**

After the context is created, the beans can be accessed directly by referring to them by their **bean name**.

Ultimately, on your code you would be importing the context and accessing the beans from there.

This decoupling  is the essence of the dependency injection, on your code you don't know where these objects are coming from, you just declare that you need them through the context.

{% hint style="success" %}
Since the context wraps the beans, we were tempted to call it, **the tortilla**, but as you can tell by our naming policy and docs, [we are serious people.](/about-us)
{% endhint %}

### **Bean definitions**

There are two types of bean definitions that can be passed to the contextFactory to be resolved into beans:

* **Hints**. (**A function or class).** ConanJs will understand that your are hinting that an object using the class or the function needs to be created, and it will create it for you.
* **Values. (An object).** ConanJs will take the provided value as the bean value. This is handy if you want to put a straight value on the context, or because you want this value to be resolved as the correct dependency for a hint.

When passing hints to the [**DiContextFactory.createContext**](/api/dependency-injection/dicontextfactory)**,** ConanJs will look for any **unresolved dependencies** for the hint, and will resolve them recursively by name (this is explained in details on the section below).

## Resolving Dependencies

Resolving each bean definition into a bean is the process called Resolving Dependencies.

Resolving **values** is straight forward, the value for the bean is exactly the same value as provided to the DiContextFactory.

**Resolving hints** is more complex, when resolving hints there are three scenarios based on the underlying function or constructor parameters.

* **No parameters**: The function/constructor is invoked, the return value is the bean.
* **With parameters:** If the hint has parameters, the **resolution by name** starts where each parameter is resolved and when all of them are resolved, the function/constructor is invoked with the parameters, the return value is the bean.

### Resolution by name

Resolution by name is the process by which a hint needs its parameters resolved.

ConanJs will obtain the name of the parameter, and resolve it agains the context.

This is where the recursive nature comes into play, basically there are two scenarios when a parameter needs to be resolved

* if there is a **value** with the same name provided in the context, is resolved to that value
* If there is a **hint** with the same name provided in the contex&#x74;**,** it recursively resolve it.

{% hint style="success" %}
If you are familiar with DI you might be aware of the different flavours of resolutions, for instance type resolution...

ConanJs being JS based, and JS not having types means that we can only support name resolution.
{% endhint %}

## Aux bean definitions

Lastly, is important to understand that you can optionally pass a second set of key value pairs of bean definitions to [DiContextFactory.create](/api/dependency-injection/dicontextfactory), these are called **Aux beans definitions.**

If you do this, ConanJs will combine both bean definitions for the purpose of resolving any bean, just as if you have passed them together, the difference is that **the context will not expose the resolved beans for the Aux beans definition.**

This is handy, as many times you will have bean definitions passed to only satisfy internal implementation details, and it doesn't make sense to have their resolved beans available in the context.

{% hint style="success" %}
Understanding the purpose of many of the concepts exposed here is difficult without real use cases, please bear while we take you through [Creating the Context](/dependency-injection/creating-the-context) and [Using the Context](/dependency-injection/using-the-context) as things should start making sense soon!
{% endhint %}


# Creating the Context

## Introduction

Let's now get hands on creating different [beans](/dependency-injection/general-concepts#the-beans) through the context.

The principle is always the same: use *DiContextFactory.createContext* to pass the [bean names](/dependency-injection/general-concepts#bean-definitions) with their [bean definitions](/dependency-injection/general-concepts#bean-definitions).

We will now show all the different use cases starting from the simple cases to the complex ones.

## Creating beans

### Adding values to the context

The simplest bean to create is a [value](/dependency-injection/general-concepts#bean-definitions):

```typescript
const diContext = DiContextFactory.createContext({
    baseUrl: 'localhost' // this is a value
});
```

Adding values let's you access them directly

```javascript
console.log(diContext.baseUrl); //This will printout 'localhost'
```

### Adding hints to the context

The real value of the dependency injection is to get it to create complex objects for you.

This is the case for [hints](/dependency-injection/general-concepts#bean-definitions), (functions or class definitions)

#### Parameterless hints

When you need to add hints, which class constructor or function are parameterless, you can do this by passing the class or the function reference directly.

```typescript
class MyAmazingClass {
    saySomething (){ return 'something'}
}

const diContext = DiContextFactory.createContext({
    myAmazingObject: MyAmazingClass, // this is class hint
});
```

```javascript
console.log(
    diContext.myAmazingObject.saySomething()
); //This will print 'something'
```

#### Internal dependencies

Now that we have seen the simplest case of parameterless hints, let's see what would happen if we needed to specify an internal dependency.

Let's also show something closer to a real world case, let's imagine that the strings to be used for MyAmazingClass could be configured from the outside as you might need to if your applications supports many locales.

```typescript
class MyAmazingClass {
    constructor (somethingStr){
        this.somethingStr = somethingStr;
    }
    
    saySomething (){ return this.somethingStr}
}

const diContext = DiContextFactory.createContext({
    myAmazingObject: MyAmazingClass, // this is class hint
},{
    somethingStr: 'something'
);
```

#### Function hints

The same principle that applies to classes can also apply to functions.

Is your choice when hinting if you want to use a full fledge class or a function that returns something.

We can see this in the following example

```typescript
function rollDice () {
    return Math.floor(Math.random() * 6) + 1  
}

const diContext = DiContextFactory.createContext({
    randomRoll: rollDice, // this is function hint
})
```

And also we can see how we can use function hints and internal dependencies.

```typescript
function rollDice (maxValue) {
    return Math.floor(Math.random() * maxValue) + 1  
}

const diContext = DiContextFactory.createContext({
    randomRoll: rollDice, // this is function hint
}, {
    maxValue: 6
})
```

### Functions/classes as values

Because functions and class are always assumed to be hints, you will find that it might now work as you expect  if you need to have a dependency to be resolved to a function or a class...

For instance:

```typescript
function sayHello (){
    return 'hello'
}
const diContext = DiContextFactory.createContext({
    sayHello
});
```

The bean definition in the example above 'sayHello' is considered to be a hint (is a function), so if you access it through the context, the actual result  would be the string 'hello'

```javascript
console.log(diContext.sayHello); //This will printout 'hello'
console.log(diContext.sayHello()); //This will throw an error
```

If you wanted the function to be used as a value, and not as a hint, you will have to wrap it into an additional function.

This will trick the framework in resolving it to your original function, for instance to receive as a bean the function sayHello, instead of its returning value:

```typescript
function sayHello (){
    return 'hello'
}

const diContext = DiContextFactory.createContext({
    sayHello: ()=>sayHello
});

console.log(diContext.sayHello()); //This will print helllo
```

{% hint style="info" %}
As of v1.0 we are hoping to provide with you with a simpler mechanism to pass functions and class as hints in one of our first next releases.
{% endhint %}

### Combining Hints and Values

The real power from dependency injection is that it lets you combine any level of hints and/or values.

```javascript
class StockService{
    constructor (stockEndpoint){
         this.stockEndpoint = stockEndpoint
    }
}

class Endpoint {
    constructor (baseUrl){
        this.baseUrl = baseUrl
    }
}

const diContext = DiContextFactory.createContext({
    stockService: StockService, // this is the hint to create a StockService
    stockEndpoint: Endpoint, // we need to populate the value for the baseUrl
},{
    baseUrl: 'localhost'
});
```

As you can see in the example above, we have:

* baseUrl: An [aux bean definition](/dependency-injection/general-concepts#aux-bean-definitions) used to initialise an Endpoint
* stockEndpoint: A hint for the class Endpoint. Note that the constructor receives a parameter named 'baseUrl', this matches the aux bean definition, which means that it will be injected into the stockEndpoint bean.
* stockService. A hint for the class StockService, the bean created in this context will receive injected through the constructor the stockEndpoint.

## Dynamic context

A side effect of working with plain objects to store the context, is that as with as any other normal object, you can use functions to generate the context, or that you can change the context after it has been created.

You will see in the next section how this combined with the other features from dependency injection will let you for example write simpler integration tests.

{% hint style="info" %}
We think that having a dynamic context is key to fully take advantage of the dependency injection

As of v1.0, we don't have any out of the box mechanism to help you create dynamic context, but we are hoping to change this in the near future.
{% endhint %}

![Come on! Next section everything come together!](/files/-MCSH9A0ReEYBw0ccAro)


# Using the Context

## Introduction

Now that you are familiar with the [concepts](/dependency-injection/general-concepts) and the basis to [create the context](/dependency-injection/creating-the-context) it makes sense to explore what are the benefits os using dependency injection.

## Benefits

### Reduce boilerplate

One of the major advantages of dependency injection is that it lets you code your components not worrying about how to wire them together

You just write the classes and functions that you are going to use so that they receive as normal whichever parameters you need them to receive.

By not having to create the objects explicitly you will already reducing the boilerplate.

### Centralise Configuration

Having a single point where all beans share their dependencies is very handy, it makes very simple to change the configuration for the entire application and to cascade changes.

Having centralised configuration also helps reducing boiler plate code, is very likely that you will share a lot of dependencies through all the beans you need to create.

As long as you hint them using the same name, you will only need to specify then once.

### Helps decoupling your components

By using dependency injection your are NOT going to automatically start to have your components more decoupled, but it will empower you to do so.

For instance, one common decoupling pattern is the strategy pattern

{% embed url="<https://en.wikipedia.org/wiki/Strategy_pattern>" %}

You could use this pattern not using dependency injection, but you would likely be overwhelmed by the amount of wiring if your were to do it yourself.

### Your application interface

When thinking about the beans you want to expose through the context, it is helpful to think of them as the interface for your entire application.

This can help you, or other members of your team to develop further components, as you can then leverage the context as if it was the API to provide as the foundation.

Obviously then, as you add more beans to your context, you will also be expanding your API

### Helps with integration testing

Derived from all the benefits mentioned already, dependency injection lets you easily write integrations tests.

To be able to fully benefit from this, you are likely going to have to change your context before you run your tests.

Doing so, lets you stub/mock complex dependencies and substitute them for integration testing.


# ASAPs

## Introduction

Asaps are very similar to promises, with two major differences:

* They can be resolved in the same thread.
* They can be cancelled

But other than that are fully compatible with promises

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>" %}

## Synchronous Execution

One of the main drives to create the ASAPs was to have an abstraction that will encapsulate promises, but that would also run them synchronously when possible.

Let's illustrate this with an example:

```javascript
var thePro = new Promise ((resolve) => resolve(5));
thePro.then ((value) => console.log(value))
console.log('hi!')

//This will print
//hi!
//5
```

As you can see, the promise resolves immediately, but the order of the execution is not what you might expect.

**Every time you use a promise, the code to resolve the promise will be run as if it was in a different not concurrent thread**

Let's compare it with an Asap.

```javascript
var thePro = Asaps.now(5);
thePro.then ((value)=>console.log(value))
console.log('hi!')

//This will print
//5
//hi!
```

In here, the Asap resolves, well.. asap&#x20;

### Why?

The goal is to simplify writing code that sometimes should resolve now, sometimes should resolve later...

If you are familiar with other state management frameworks like Redux, you might be a know a side effect of this, when you perform a synchronous operation that changes the state, but you can't query the state immediately after.

This small inconvenience then starts leaking all over the framework, all of the sudden you have to write callbacks for everything to guarantee that the state you want to read is up to date.

With ConanJs you will be able to query directly the state after performing an action that updates it synchronously. This is because ASAPs are used behind the scenes.

## Creating ASAPS

You can create an Asap through the Asaps class. In here you can find its main 3 methods.

{% hint style="success" %}
To see all the available methods, like resolving an Asap on the back of a fetch check the [Asaps API docs](/api/asaps/asaps).&#x20;
{% endhint %}

### fromPromise

If you have a promise, all you have to do is use this method to create an Asap from it.

```javascript
let myAsap = Asasp.fromPromise(myPromise) 
```

### now

Lets you create a promise that resolves now to a value

```javascript
let myAsap = Asasp.now(5) 
```

### next

Lets you create a promise that will be resolved synchronously, but it also lets you defer the value to resolve later on the same thread.

This method is the cornerstone of the reason of Asaps to exist, let's illustrate this with an example.

```javascript
// returns a tuple, the first value is the atual asap
// the second is a function to resolve the value
let [asap, next] = Asasp.next() 

console.log(1)
asap.then((value)=>console.log(value))
next(2)
console.log(3)

// This will print
// 1
// 2
// 3
```

## Life Cycle Interface

Asaps have a life cycle that matches the one for promises, with the added state of the Asap being cancelled.

Note that it is out of the scope of this documentation to explain how a promise works, so we are going to assume that you are familiar with them.

The two main life cycle methods for a promise are then and catch, in ConanJs we also have onCancel.

### then

Similar to a normal promise, you can append listeners to execute once that the promise is resolved successfully.

### catch

These listeners will be executed in case of an error triggered while resolving the underlying Asap.

### onCancel

Lastly, you can also add listeners to be executed when the promise has been cancelled.

{% hint style="success" %}
As of v1.0 we don't have a finally callback, but this would be added soon.
{% endhint %}

## Cancelling Asaps

Whether a promise should be cancellable or not will likely spark flame wars, and we do understand why:

* If you cancel an async operation, but you don't cancel everything that operation has started, can it really be cancelled?
* How do you cancel a network call already started?

These are very difficult questions to answer and they have stalled any potential progress into providing this mechanism built in for Promises.

But we think that this is not fair for the developer, that an operation is dangerous and delicate, should not mean that is also very complicated to trigger.

That is why we provide with [**asap.cancel ()**.](/api/asaps/asap) if you call it, it will not resolve (then and catch will not be invoked), and instead all onCancel listeners will be invoked.

Would this mean that is going to cancel everything that you started? **NO**

You will need to make sure that you react to the cancellation according to your business use case, and do as much housekeeping as needed, but at least you get to choose if you want to go down this route.


# Logging

## Introduction

Logging is built-in with ConanJs to provide you with an integrated platform so that you can:

* Log meaningful message easily
* Log what is happening internally in ConanJs
* Fine tune at runtime what should be logged.

ConanData and Asaps both produce ConanJs log messages out of the box.

{% hint style="success" %}
As of v1.0 dependency injection does not log anything at the moment, but this will be the case soon.
{% endhint %}

## Anatomy

A logging message has many attributes that are helpful to understand where the message comes from, its information, and also, to make easier to fine tune what should be logged out.

### Nature (Where?)

Indicates the nature of the source of this log message. There are seven natures:

| Name       | Source                                                                                                                          |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------- |
| **MAIN**   | The [main thread](/data/conan-state/life-cycle#the-main-thread) in a Conan state                                                |
| **META**   | The [meta flow](/data/conan-state/life-cycle#the-meta-flow) in a Conan state                                                    |
| **ASYNC**  | The [monitor thread](/data/conan-state/life-cycle#the-monitor-thread) in a Conan state                                          |
| **HELPER** | The [main thread](/data/conan-state/life-cycle#the-main-thread) in a Conan state (when the user decides to override the nature) |
| **ASAP**   | Log message from an [ASAP](/asaps).                                                                                             |
| **AUX**    | Derived from a Conan State that is created internally by the framework (you are likely to want to have this always turned off)  |

### Level (How important?)

There are 7 levels. In order of importance (from less important to more important):

* **DEBUG**
* **TRACE**
* **INFO**
* **MILESTONE**
* **WARN**
* **ERROR**

### shortDesc

A string message describing what is happening

### payload

Optionally, there can a payload that will also get logged out.

## Fine tuning Logging.

You can configure what to log at runtime. By default it gets log out everything that is:

**MAIN** and **MILESTONE**

To fine tune what gets logged out there are three main methods

#### updateLoggingFilter

Receives the current rules for logging, returns the new rules for logging

#### setLoggingFilter

Sets the logging rules

#### getLoggingFilter

Get the current rules.

## Demo

The following example illustrates how to change the logging levels at runtime

{% embed url="<https://codesandbox.io/s/2dqbx>" %}


# Main Classes


# Conan

The class Conan contains the following methods:

### ***light\<DATA>***

*light* is the method we use to create a simple Conan State without passing reducers and actions

| Input Params |                                                                                                                                |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| name         | <p><strong>Type:</strong>  <code>string </code><em><code>required</code></em></p><p>the name we want to use for this state</p> |
| initialData  | <p><strong>Type:</strong>  <code>DATA</code></p><p> the initial data we want to have when the state is created</p>             |
| nature       | <p><strong>Type:</strong>  FlowEventNature </p><p>TBC: Que mierdas es esto Alberto?</p>                                        |

| Returns    |                         |
| ---------- | ----------------------- |
| ConanState | The newly created state |

### ***state\<DATA, REDUCERS extends Reducers\<DATA> = {}, ACTIONS = any>***

*state* is the method we use to create a Conan State when we need to add extra reducers and or actions

| Params     |                                                                                                                                                             |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ***data*** | <p><strong>Type:</strong>  <code>StateDef </code><em><code>required</code></em></p><p>the StateDef object that contains our custom actions and reducers</p> |

| Return type |                         |
| ----------- | ----------------------- |
| ConanState  | The newly created state |


# StateDef

the class StateDef holds the definition of a state, that can be passed to [Conan.state](/api/main-classes/conan)

| Params           |                                                                                                                                                                                                                         |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name             | <p><strong>Type:</strong>  <code>string </code><em><code>required</code></em></p><p>the name we want to use for this state</p>                                                                                          |
| initialData      | <p><strong>Type:</strong>  <code>AsapLike\<DATA> </code><em><code>required</code></em> </p><p> the initial data we want to have when the state is created</p>                                                           |
| reducers         | <p><strong>Type:</strong>  <code>ReducersFn\<DATA, REDUCERS> </code><em><code>optional</code></em></p><p>the reducers that will act on this state</p>                                                                   |
| actions          | <p><strong>Type:</strong>  <code>ActionsFn\<DATA, REDUCERS, IPartial\<ACTIONS>> </code><em><code>optional</code></em></p><p>the actions that will act on this state</p>                                                 |
| autoBind         | <p><strong>Type:</strong>  <code>any </code><em><code>optional</code></em></p><p>any object with logic we want to auto bind with this state</p>                                                                         |
| pipelineListener | <p><strong>Type:</strong>  <code>IConsumer\<FlowEvent> </code><em><code>optional</code></em></p><p><strong>TBC: Que mierdas es esto Alberto?</strong></p>                                                               |
| cancelAutoStart  | <p><strong>Type:</strong>  <code>boolean </code><em><code>optional</code></em></p><p>true if we want to cancel the auto start of the state</p>                                                                          |
| reactions        | <p><strong>Type:</strong>  <code>RUserReactionsDef<{ nextData: DATA }, 'nextData', { nextData: ACTIONS & REDUCERS }> </code><em><code>optional</code></em></p><p><strong>TBC: Que mierdas es esto Alberto?</strong></p> |
| nature           | <p><strong>Type:</strong>  <code>FlowEventNature </code><em><code>optional</code></em></p><p><strong>TBC: Que mierdas es esto Alberto?</strong></p>                                                                     |

|   |   |
| - | - |
|   |   |


# ConanState

The class ConanState contains the following methods:

### ***connectMap \<PROPS>***

this method allows connecting a Conan state with a React component, using a mapper function to describe the mapping

| Input     |                                                                                                                                                                                                              |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| toConnect | <p><strong>Type:</strong>  <code>React.ComponentType </code><em><code>required</code></em></p><p>the component type we want to connect</p>                                                                   |
| mapper    | <p><strong>Type:</strong>  <code>IBiFunction\<DATA, ACTIONS, PROPS> </code><em><code>required</code></em></p><p> A function that receives DATA and ACTIONS. It describes how the PROPS will be connected</p> |

| Returns      |                           |
| ------------ | ------------------------- |
| ReactElement | A connected React element |

### ***connectData***

this method allows connecting all Conan state data with a React component,

| Input     |                                                                                                                                            |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| toConnect | <p><strong>Type:</strong>  <code>React.ComponentType </code><em><code>required</code></em></p><p>the component type we want to connect</p> |

| Returns      |                           |
| ------------ | ------------------------- |
| ReactElement | A connected React element |

### ***connect***

‌this method allows connecting all Conan state  with a React component

| Input     | ​Title                                                                                                                                                                     |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| toConnect | <p><strong>Type:</strong> <code>React.ComponentType\<ConnectedState\<DATA, ACTIONS>> </code><em><code>required</code></em></p><p>the component type we want to connect</p> |

| Returns                       | ​Title                                        |
| ----------------------------- | --------------------------------------------- |
| ReactElement\<ConnectedState> | A React element with the whole ConnectedState |

### ***connectLive***

‌this method allows producing connected react elements by accepting a renderer function, which receives the ConanState data and actions.

| Input         | ​Title                                                                                                   |                                                                                                                                     |
| ------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| renderer      | <p><strong>Type:</strong> <code>IBiFunction\<DATA, ACTIONS, ReactElement                                 | ReactElement\[]> </code><em><code>required</code></em></p><p>The render function that will produce out connected react elements</p> |
| fallbackValue | <p><strong>Type:</strong> DATA optional</p><p>default DATA in case nothing is there when initialised</p> |                                                                                                                                     |

| Returns      | ​Title                          |
| ------------ | ------------------------------- |
| ReactElement | A State connected React element |

### ***addDataReaction***

‌this method can be uses to add a custom data reaction a un ConanState

| Input | ​Title                                                                                                                                     |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| def   | <p><strong>Type:</strong> <code>DataReactionDef\<DATA> </code><em><code>required</code></em></p><p>the custom data reaction definition</p> |

| Returns          | ​Title                        |
| ---------------- | ----------------------------- |
| DataReactionLock | TBC: Alberto que coño es esto |

### ***do***

‌this method returns the actions available for this ConanState

| Input | ​Title |
| ----- | ------ |
| void  |        |

| Returns          | ​Title                                |
| ---------------- | ------------------------------------- |
| DataReactionLock | actions available for this ConanState |

### *getData*

‌this method returns the current data of this ConanState

| Input | ​Title |
| ----- | ------ |
| void  |        |

| Returns | ​Title                          |
| ------- | ------------------------------- |
| DATA    | current data of this ConanState |

### *filter*

‌this method returns a filtered ConanState

| Input  | ​Title                                                                                                                                                                                                                              |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| mapper | <p><strong>Type:</strong> <code>(current: DATA, previous: DATA) => boolean </code><em><code>required</code></em></p><p><code>the filter function that receives the current and previous DATA and has to return a boolean</code></p> |

| Returns           | ​Title                            |
| ----------------- | --------------------------------- |
| ConanState\<DATA> | The resulting filtered ConanState |

### *map\<T>*

‌this method returns a remapped ConanState

| Input  | ​Title                                                                                                                                                                                                             |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| mapper | <p><strong>Type:</strong> <code>IFunction\<DATA, T> </code><em><code>required</code></em></p><p><code>the mapper function that receives the current DATA and has to return the new remmapped ConanState</code></p> |

| Returns           | ​Title                            |
| ----------------- | --------------------------------- |
| ConanState\<DATA> | The resulting remapped ConanState |

### *merge\<T, TO\_MERGE>*

‌this method returns a remapped ConanState

| Input    | ​Title                                                                                                                                                                            |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| toMerge$ | <p><strong>Type:</strong> <code>ConanState\<TO\_MERGE, any> </code><em><code>required</code></em></p><p><code>the ConanState that we want to merge with</code></p>                |
| merger   | <p><strong>Type:</strong> <code>ITriFunction\<DATA, TO\_MERGE, T, T> </code><em><code>required</code></em></p><p><code>the function that describes the merge operation</code></p> |

| Returns        | ​Title                          |
| -------------- | ------------------------------- |
| ConanState\<T> | The resulting merged ConanState |

### *tuple\<TO\_MERGE>*

‌this method combined two states into one

| Input    | ​Title                                                                                                                                                             |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| toMerge$ | <p><strong>Type:</strong> <code>ConanState\<TO\_MERGE, any> </code><em><code>required</code></em></p><p><code>the ConanState that we want to merge with</code></p> |

| Returns                        | ​Title                            |
| ------------------------------ | --------------------------------- |
| ConanState<\[DATA, TO\_MERGE]> | The resulting combined ConanState |

### *asyncState*

‌this method gives access to the async state data and actions

| Input | ​Title |
| ----- | ------ |
| void  |        |

| Returns                                  | ​Title                           |
| ---------------------------------------- | -------------------------------- |
| ConanState\<MonitorInfo, MonitorActions> | the async state data and actions |

### *metaFlow* <a href="#asyncstate" id="asyncstate"></a>

‌‌this method gives access to the state meta flow

| Input | ​Title       |
| ----- | ------------ |
| void  | **​**Content |

| Returns                                | ​Title                             |
| -------------------------------------- | ---------------------------------- |
| ConanFlow\<MetaStatuses, MetaMutators> | the meta Conan flow for this state |

### *combine\<T extends {}, ACTIONS = void>*

‌this method combined two states into one

| Input         | ​Title                                                                                                                                                                             |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name          | <p><strong>Type:</strong> <code>String </code><em><code>required</code></em></p><p><code>The name for the combined ConanState that will be returned</code></p>                     |
| fromState     | <p><strong>Type:</strong> <code>{\[KEY in keyof T]: ConanState\<T\[KEY], any>} </code><em><code>required</code></em></p><p><code>the ConanState that we want to combine</code></p> |
| pipeThreadDef | <p><strong>Type:</strong> <code>PipeThreadDef\<T, {}, ACTIONS> </code><em><code>optional</code></em></p><p><code>TBC: Alberto que coño es esto</code> </p>                         |

| Returns                 | ​Title                            |
| ----------------------- | --------------------------------- |
| ConanState\<T, ACTIONS> | The resulting combined ConanState |

### *getEvents*

‌this method gives access to the ConanState main thread events

| Input | ​Title |
| ----- | ------ |
| void  |        |

| Returns                              | ​Title                                                      |
| ------------------------------------ | ----------------------------------------------------------- |
| FlowEventsTracker<{ nextData: DATA}> | all the events that have gone through the state main thread |

### *getName*

‌this method returns the ConantState name

| Input | ​Title |
| ----- | ------ |
| void  |        |

| Returns | ​Title              |
| ------- | ------------------- |
| string  | the ConanState name |

### *openTransaction*

‌this method allows to open a transaction

| Input | ​Title                                                                                                                                                                         |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| name  | <p><strong>Type:</strong> <code>String </code><em><code>required</code></em></p><p><code>The name of the transaction to create to be used for internal logging only</code></p> |

| Returns | ​Title |
| ------- | ------ |
| void    |        |

### *closeTransaction*

‌this method allows to close the current transaction

| Input    | ​Title                                                                                                                                                              |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| callback | <p><strong>Type:</strong> <code>IConsumer\<DATA> </code><em><code>optional</code></em></p><p><code>callback to be invoked once the transaction is closed</code></p> |

| Returns | ​Title |
| ------- | ------ |
| void    |        |


# ConanFlow

The class ConanFlow contains the following methods:

### ***on***

this method allows connecting a Conan state with a React component, using a mapper function to describe the mapping

| Input      |                                                                                                                         |
| ---------- | ----------------------------------------------------------------------------------------------------------------------- |
| statusName | <p><strong>Type:</strong>  <code>STATUS </code><em><code>required</code></em></p><p>the STATUS we want to hook into</p> |

| Returns                            |                                                                                                             |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| StatusDef\<USER\_STATUSES, STATUS> | The StatusDef object allows to add reactions, invoke transitions, steps and obtain the last ConanState Data |

### ***start***

this method allows connecting a Conan state with a React component, using a mapper function to describe the mapping

| Input         |                                                                                                                                                             |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| initialStatus | <p><strong>Type:</strong>  <code>StatusLike\<USER\_STATUSES> </code><em><code>optional</code></em></p><p>optional initial STATUS to start the flow with</p> |

| Returns   |                |
| --------- | -------------- |
| ConanFlow | this ConanFlow |

###

### *toStateAll*

this method creates a ConanState with the state of each status

| Returns             |                                          |
| ------------------- | ---------------------------------------- |
| ConanState\<Status> | contains the states for all the statuses |

### *toState*

this method creates a ConanState with the state of the status passed as input

| Input  |                                                                                                                                         |
| ------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| status | <p><strong>Type:</strong>  <code>STATUS </code><em><code>required</code></em></p><p>the STATUS we want to obtain the ConanState for</p> |

| Returns                              |                                  |
| ------------------------------------ | -------------------------------- |
| ConanState\<USER\_STATUSES\[STATUS]> | ConanState for the status passed |


# UserFlowDef

This interface allows defining a ConanFlow.

| Property         | Description                                                                                                                                                                         |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name             | <p><strong>Type:</strong>  <code>string </code><em><code>required</code></em></p><p>the name of the flow</p>                                                                        |
| statuses         | <p><strong>Type:</strong>  <code>UserFlowStatusesDef\<STATUSES, MUTATORS> </code><em><code>required</code></em></p><p><code>The statuses definition this flow will have</code></p>  |
| initialStatus    | <p><strong>Type:</strong>  <code>AsapLike\<StatusLike\<STATUSES>> </code><em><code>optional</code></em></p><p><code>The initial status to start with</code></p>                     |
| actions          | <p><strong>Type:</strong>  <code>FlowActionsDef\<STATUSES, MUTATORS, ACTIONS> </code><em><code>optional</code></em></p><p>The actions this flow will execute</p>                    |
| $onInit          | <p><strong>Type:</strong>  <code>ReactionCb\<STATUSES, any> \[] </code><em><code>optional</code></em></p><p>The array of reactions to execute when the ConanFlow is initialised</p> |
| $onStop          | <p><strong>Type:</strong>  <code>ReactionCb\<STATUSES, any> \[] </code><em><code>optional</code></em></p><p>The array of reactions to execute when the ConanFlow is stopped</p>     |
| pipelineListener | <p><strong>Type:</strong>  <code>IConsumer\<FlowEvent> </code><em><code>optional</code></em></p><p>A listener can be attached to flow events</p>                                    |
| loggingRule      | <p><strong>Type:</strong>  <code>Rule\<FlowEvent> </code><em><code>optional</code></em></p><p>the default logging policy can be overridden by passing a custom Rule</p>             |
| nature           | <p><strong>Type:</strong>  <code>FlowEventNature </code><em><code>optional</code></em></p><p><strong>TBC: Alberto qué coño es esto</strong></p>                                     |


# UserStatusDef

This is the type that is used to define a status for a Flow

| Property                 | Description                                                                                                                                                                        |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p>reactions</p><p>�</p> | <p><strong>Type:</strong>  <code>string </code><em><code>optional</code></em></p><p>the name of the flow</p>                                                                       |
| statuses                 | <p><strong>Type:</strong>  <code>UserFlowStatusesDef\<STATUSES, MUTATORS> </code><em><code>required</code></em></p><p><code>The statuses definition this flow will have</code></p> |
| initialStatus            | **Type:**  `AsapLike<StatusLike<STATUSES>>`` `*`optional`*                                                                                                                         |

�


# Status

This interface defines a Status that will be used in a ConanFlow

�

```typescript
export interface Status <
    STATUSES_FROM = any,
    KEY extends keyof STATUSES_FROM = any,
> {
    name: KEY,
    data?: STATUSES_FROM[KEY],
}
```

&#x20;

| Property | Description                                                                                                                        |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| name     | <p><strong>Type:</strong>  <code>KEY </code><em><code>required</code></em></p><p>the name of the status</p>                        |
| data     | <p><strong>Type:</strong>  <code>STATUSES\_FROM\[KEY] </code><em><code>optional</code></em></p><p><code>The status data</code></p> |


# Conan State Classes


# Thread

The class Thread has the following methods:

### ***getData***

this method returns the Thread's attached DATA

| Returns |          |
| ------- | -------- |
| DATA    | the date |

### ***start***

this method starts the Thread

| Returns |   |
| ------- | - |
| void    | - |

### ***stop***

this method stops the Thread

| Input          |                                                                                                                                                                            |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| eventsConsumer | <p><strong>Type:</strong>  <code>(events) => void </code><em><code>required</code></em></p><p>a function that will receive all the events until the thread was stopped</p> |

| Returns |   |
| ------- | - |
| void    |   |

### ***next***

this method will call the callback passed as param when the thread's state changes

| Input |                                                                                                                                                                                   |
| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| cb    | <p><strong>Type:</strong>  <code>(onNext: Context\<ThreadFlow\<DATA>, 'nextData', { nextData: REDUCERS }>) </code><em><code>required</code></em></p><p>the callback to invoke</p> |

| Returns |   |
| ------- | - |
| void    |   |

�

### ***addReaction***

this method allows to add a reaction on the thread

| Input |                                                                                                                                      |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------ |
| def   | <p><strong>Type:</strong>  <code>DataReactionDef\<DATA> </code><em><code>required</code></em></p><p>the data reaction definition</p> |

| Returns          |                                 |
| ---------------- | ------------------------------- |
| DataReactionLock | TBC: Alberto qué mierda es esto |

### ***chain***

this method allows to chain a callback to the next data update

| Input      |                                                                                                                                                    |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| mutatorsCb | <p><strong>Type:</strong>  <code>IConsumer\<REDUCERS & DefaultStepFn\<DATA>> </code><em><code>required</code></em></p><p>the callback to chain</p> |
| name       | <p><strong>Type:</strong>  <code>string </code><em><code>optional</code></em></p><p>the name passed will be eaten by the framework and ignored</p> |

| Returns     |                                   |
| ----------- | --------------------------------- |
| Asap\<DATA> | The up to date DATA of the Thread |

### ***monitor\<T>***

this method allows to perform async operations within a thread in a controlled way

| Input        |                                                                                                                                                                                      |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| toMonitor    | <p><strong>Type:</strong>  <code>Asap\<T> </code><em><code>required</code></em></p><p>the Asap we want to monitor</p>                                                                |
| thenCallback | <p><strong>Type:</strong>  <code>IBiConsumer\<T, REDUCERS & DefaultStepFn\<T>> </code><em><code>required</code></em></p><p>callback function to invoke when the Asap is resolved</p> |
| payload      | <p><strong>Type:</strong>  <code>any </code><em><code>optional</code></em></p><p>payload used for logging</p>                                                                        |
|              |                                                                                                                                                                                      |

| Returns     |                                   |
| ----------- | --------------------------------- |
| Asap\<DATA> | The up to date DATA of the Thread |

### ***isRunning***

true of the underlying flow is running

| Returns |   |
| ------- | - |
| Boolean | - |

### ***reducers***

returns the underlying flow reducers

| Returns                         |   |
| ------------------------------- | - |
| REDUCERS & DefaultStepFn\<DATA> |   |

### ***getEvents***

returns the underlying flow events

| Returns                               |   |
| ------------------------------------- | - |
| FlowEventsTracker<{ nextData: DATA }> |   |

### ***getName***

returns the underlying flow name

| Returns |   |
| ------- | - |
| string  |   |

### ***changeLoggingNature***

gives access to changing the underlying flow logging nature

| Input  |                                                                                                                         |
| ------ | ----------------------------------------------------------------------------------------------------------------------- |
| nature | <p><strong>Type:</strong>  <code>FlowEventNature </code><em><code>required</code></em></p><p>the new logging nature</p> |

| Returns |   |
| ------- | - |
| void    | - |

### ***log***

logs a message

| Input |                                                                                                            |
| ----- | ---------------------------------------------------------------------------------------------------------- |
| msg   | <p><strong>Type:</strong>  <code>string </code><em><code>required</code></em></p><p>the message to log</p> |

| Returns |   |
| ------- | - |
| void    |   |

### ***once***

adds a reaction once to the underlying flow

| Input    |                                                                                                                                 |
| -------- | ------------------------------------------------------------------------------------------------------------------------------- |
| reaction | <p><strong>Type:</strong>  <code>IConsumer\<DATA> </code><em><code>required</code></em></p><p>the reaction to add</p>           |
| name     | <p><strong>Type:</strong>  <code>string </code><em><code>optional</code></em></p><p>reaction name used for logging purposes</p> |

| Returns |   |
| ------- | - |
| this    |   |


# ConnectedState

This interface contains all the information required to access a Conan state. It is the state components use once they are connected:

```typescript
export interface ConnectedState<DATA, ACTIONS> {
    data: DATA,
    actions: ACTIONS,
    monitorInfo: MonitorInfo
}
```

�

| Property    | Description                                                                                                                         |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| data        | <p><strong>Type:</strong>  <code>DATA</code> </p><p>the data part of the Conan state</p>                                            |
| actions     | <p><strong>Type:</strong>  <code>ACTIONS</code></p><p><code>The Conan state actions</code></p>                                      |
| monitorInfo | <p><strong>Type:</strong>  <code>MonitorInfo</code> </p><p><code>The MonitorInfo object associated with this Conan state</code></p> |


# MonitorInfo

This interface gives access to all the useful bits related to asynchronous operations:

```typescript
export interface MonitorInfo {
    inProgressActions?: AsynAction<any>[],
    currentAction?: AsynAction<any>,
    status?: MonitorStatus,
}
```

�

| Property          | Description                                                                                                                      |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| inProgressActions | <p><strong>Type:</strong>  <code>AsynAction\<any>\[]</code> </p><p>all the actions currently in progress in this Conan state</p> |
| currentAction     | <p><strong>Type:</strong>  <code>AsynAction\<any></code></p><p><code>The current action being executed</code></p>                |
| status            | <p><strong>Type:</strong>  <code>MonitorStatus</code> </p><p><code>The current status of this monitor</code></p>                 |

The possible values for MonitorStatus are:

```typescript
export enum MonitorStatus {
    IDLE = 'IDLE',
    ASYNC_START = "ASYNC_START",
    ASYNC_FULFILLED = "ASYNC_FULFILLED",
    ASYNC_CANCELLED = "ASYNC_CANCELLED",
}
```

�


# MetaInfo

This interface models the meta information associated with a meta flow:

```typescript
export interface MetaInfo {
    transactionCount: number,
    status?: MetaStatus,
    lastError: any
}
```

�

| Property         | Description                                                                                                     |
| ---------------- | --------------------------------------------------------------------------------------------------------------- |
| transactionCount | <p><strong>Type:</strong>  <code>number</code></p><p>transaction count executed in the meta flow</p>            |
| status           | <p><strong>Type:</strong>  <code>MetaStatus</code></p><p><code>The current status of the meta flow</code></p>   |
| lastError        | <p><strong>Type:</strong>  <code>any</code> </p><p><code>last error that was thrown to the meta flow</code></p> |

The possible values for MetaStatus are:

```typescript
export enum MetaStatus {
    STARTING = 'STARTING',
    INIT = "INIT",
    RUNNING = "RUNNING",
    ERROR = "ERROR",
    IDLE = "IDLE",
    IDLE_ON_TRANSACTION = "IDLE_ON_TRANSACTION",
}
```

�


# Dependency Injection


# DiContextFactory

Conan Factory to create the context to use for Dependency injection.

### ***createContext \<T, AUX  = void>***

creates the DI context

| Input      |                                                                                                                                       |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| contextDef | <p><strong>Type:</strong>  <code>DiContextDef\<T> </code><em><code>required</code></em></p><p>context definition</p>                  |
| aux        | <p><strong>Type:</strong>  <code>DiContextDef\<AUX> </code><em><code>optional</code></em></p><p>auxiliary dependencies definition</p> |

| Returns |   |
| ------- | - |
| T & AUX |   |


# ASAPS


# Asaps

This class has a set of helper methods to handle Asaps:

### ***now\<T>***

this method resolves a passed value as an Asap synchronously

| Input |                                                                                                          |
| ----- | -------------------------------------------------------------------------------------------------------- |
| value | <p><strong>Type:</strong>  <code>T</code><em><code>required</code></em></p><p>the callback to invoke</p> |

| Returns  |   |
| -------- | - |
| Asap\<T> |   |

### ***fromPromise\<T>***

this method creates an Asap from a Promise

| Input   |                                                                                                                                 |
| ------- | ------------------------------------------------------------------------------------------------------------------------------- |
| promise | <p><strong>Type:</strong>  <code>Promise\<T></code><em><code>required</code></em></p><p>the Promise to create the Asap from</p> |
| name    | <p><strong>Type:</strong>  <code>string </code><em><code>optional</code></em></p><p>name use mainly for logging purposes</p>    |

| Returns  |   |
| -------- | - |
| Asap\<T> |   |

### ***delay*** <a href="#frompromise-less-than-t-greater-than" id="frompromise-less-than-t-greater-than"></a>

‌this method creates a delayed asynchronous Asap from a the value and timeout provided

| Input | ​Title                                                                                                                      |                                                                                                |
| ----- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| value | <p><strong>Type:</strong> <code>T                                                                                           | IProducer\<T></code><em><code>required</code></em></p><p>the value to create the Asap from</p> |
| ms    | <p><strong>Type:</strong> <code>number</code><em><code>required</code></em></p><p>the delay in milliseconds</p>             |                                                                                                |
| name  | <p><strong>Type:</strong> <code>string</code> <em><code>optional</code></em></p><p>name use mainly for logging purposes</p> |                                                                                                |

| Returns  | ​Title   |
| -------- | -------- |
| Asap\<T> | ​Content |

### ***fetch\<T>*** <a href="#frompromise-less-than-t-greater-than" id="frompromise-less-than-t-greater-than"></a>

‌this method performs a fetch from the given url, and it wraps it up in an Asap

| Input | ​Title                                                                                                   |
| ----- | -------------------------------------------------------------------------------------------------------- |
| url   | <p><strong>Type:</strong>  <code>string </code><em><code>required</code></em></p><p>the url to fetch</p> |

| Returns  | ​Title   |
| -------- | -------- |
| Asap\<T> | ​Content |

### ***next\<T>*** <a href="#frompromise-less-than-t-greater-than" id="frompromise-less-than-t-greater-than"></a>

‌this method lets you create a promise that will be resolved synchronously

| Input  | ​Title                                                                                                                      |
| ------ | --------------------------------------------------------------------------------------------------------------------------- |
| name   | <p><strong>Type:</strong> <code>string</code> <em><code>optional</code></em></p><p>name use mainly for logging purposes</p> |
| nature | <p><strong>Type:</strong> <code>FlowEventNature</code> <em><code>optional</code></em></p><p>custom log nature</p>           |

| Returns                    | ​Title                             |
| -------------------------- | ---------------------------------- |
| \[IConsumer\<T>, Asap\<T>] | ​The Asap returned can be resolved |


# Asap

This interface defines the helper methods around a Conan Asap

```typescript
export interface Asap<T> {
    catch(error: IConsumer<Error>): this;

    then(consumer: IConsumer<T>): this;

    onCancel(consumer: ICallback): this;

    map<Z>(mapper: IFunction<T, Z>): Asap<Z>;

    chain<Z>(chainProducer: IFunction<T, Asap<Z>>): Asap<Z>;

    type: AsapType;

    cancel(): boolean;
}
```

�

### ***catch***

it will be invoked when an error is thrown while resolving the Asap's Promise

| Input |                                                                                                                          |
| ----- | ------------------------------------------------------------------------------------------------------------------------ |
| error | <p><strong>Type:</strong>  <code>IConsumer\<Error></code><em><code>required</code></em></p><p>the function to invoke</p> |

| Returns |   |
| ------- | - |
| this    |   |

### then <a href="#catch" id="catch"></a>

‌it will be invoked when the Asap's Promise is resolved

| Input    | ​Title                                                                                                              |
| -------- | ------------------------------------------------------------------------------------------------------------------- |
| consumer | <p><strong>Type:</strong> <code>IConsumer\<T></code><em><code>required</code></em></p><p>the function to invoke</p> |

| Returns | ​Title |
| ------- | ------ |
| this    | ​      |

### chain\<Z> <a href="#catch" id="catch"></a>

‌allows chaning Asaps

| Input         | ​Title                                                                                                                        |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| chainProducer | <p><strong>Type:</strong> <code>IFunction\<T, Asap\<Z>></code><em><code>required</code></em></p><p>the function to invoke</p> |

| Returns | ​Title |
| ------- | ------ |
| this    | ​      |

### map\<Z> <a href="#catch" id="catch"></a>

‌maps an Asap into a another one

| Input  | ​Title                                                                                                                 |
| ------ | ---------------------------------------------------------------------------------------------------------------------- |
| mapper | <p><strong>Type:</strong> <code>IFunction\<T, Z></code><em><code>required</code></em></p><p>the function to invoke</p> |

| Returns  | ​Title              |
| -------- | ------------------- |
| Asap\<Z> | ​the re-mapped Asap |

### map\<Z> <a href="#catch" id="catch"></a>

‌maps an Asap into a another one

| Input  | ​Title                                                                                                                                      |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| mapper | <p><strong>Type:</strong> <code>IFunction\<T, Z></code><em><code>required</code></em></p><p>the function producing the new chained Asap</p> |

| Returns  | ​Title            |
| -------- | ----------------- |
| Asap\<Z> | ​the chained Asap |

### cancel <a href="#catch" id="catch"></a>

‌cancels an Asap

| Returns |
| ------- |

| ​Title |   |
| ------ | - |
| void   | ​ |


