# Overmind

frictionless state management

> Web application development is about **defining**, **changing** and **consuming state** to produce a user experience. Overmind aims for a developer experience where that is all you focus on, reducing the orchestration of state management to a minimum. Making you a **happier** and more **productive** developer!

{% embed url="<https://overmindjs.changefeed.app/general/v26>" %}

## APPLICATION INSIGHT

Develop the application state, effects and actions without leaving [VS Code](https://code.visualstudio.com/), or use the standalone development tool. Everything that happens in your app is tracked and you can seamlessly code and run logic to verify that everything works as expected without necessarily having to implement UI.

![](/files/-Ly_HBec6C-YihjahYdA)

## A SINGLE STATE TREE

Building your application with a single state tree is the most straight forward mental model. You get a complete overview, but can still organize the state by namespacing it into domains. This gives you the benefit of being able to explore all the state of your application from a single point. With Typescript it is even documented. The devtools allows you to edit and mock out state.

```typescript
{
  isAuthenticating: false,
  dashboard: {
    issues: [],
    selectedIssueId: null,
  },
  user: null,
  form: new Form()
}
```

## SEPARATION OF LOGIC

Separate 3rd party APIs and logic not specific to your application by using **effects**. This will keep your application logic pure and without low level APIs cluttering your code.

{% tabs %}
{% tab title="api.js" %}

```javascript
export const fetchItems = async () {
    const response = await fetch('/api/items')

    return response.json()
  }
}
```

{% endtab %}

{% tab title="actions.js" %}

```typescript
export const loadApp = ({ state, effects }) => {
  state.items = await effects.api.fetchItems()
}
```

{% endtab %}
{% endtabs %}

## SAFE AND PREDICTABLE CHANGES

When you build applications that perform many state changes things can get out of hand. In Overmind you can only perform state changes from **actions** and all changes are tracked by the development tool. Even effects are tracked and reactions are tracked.

```javascript
export const getItems = async ({ state, effects }) => {
  state.isLoadingItems = true
  state.items = await effects.api.fetchItems()
  state.isLoadingItems = false
}
```

## COMPLEXITY TOOLS

Even though Overmind can create applications with plain **state** and **actions**, you can use **opt-in** tools like **functional operators**,**, statemachines** and state values defined as a **class,** to manage complexities of your application.

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

```javascript
export const search = pipe(
  mutate(({ state }, query) => {
    state.query = query
  }),
  filter((_, query) => query.length > 2),
  debounce(200),
  mutate(async ({ state, effects }, query) => {
    state.isSearching = true
    state.searchResult = await effects.getSearchResult(query)
    state.isSearching = false
  })
)
```

{% endtab %}

{% tab title="Statemachines" %}

```typescript
export const state = statemachine({
  unauthenticated: ['authenticating'],
  authenticating: ['unauthenticated', 'authenticated'],
  authenticated: ['unauthenticating'],
  unauthenticating: ['unauthenticated', 'authenticated']
}, {
  state: 'unauthenticated',
  user: null,
  error: null
})
```

{% endtab %}

{% tab title="Class state" %}

```javascript
class LoginForm() {
  private username = ''
  private password = ''
  private validationError = ''
  changeUsername(username) {
    this.username = username
  }
  changePassword(password) {
    if (!password.match([0-9]) {
      this.validationError = 'You need some numbers in your password'
    }
    this.password = password
  }
  isValid() {
    return Boolean(this.username && this.password) 
  }
}

export const state = {
  loginForm: new LoginForm()
}
```

{% endtab %}
{% endtabs %}

## SNAPSHOT TESTING OF LOGIC

Bring in your application configuration of state, effects and actions. Create mocks for any effects. Take a snapshot of mutations performed in an action to ensure all intermediate states are met.

```javascript
import { createOvermindMock } from 'overmind'
import { config } from './'

test('should get items', async () => {
  const overmind = createOvermindMock(config, {
    api: {
      fetchItems: () => Promise.resolve([{ id: 0, title: "foo" }])
    }
  })

  await overmind.actions.getItems()

  expect(overmind.mutations).toMatchSnapshot()
})
```

## WE WROTE THE TYPING

Overmind has you covered on typing. If you choose to use Typescript the whole API is built for excellent typing support. You will not spend time telling Typescript how your app works, Typescript will tell you!

## RUNNING CODESANDBOX

![](/files/-LyeprUbhOErEqwCnRkJ)

Overmind is running the main application of [codesandbox.io](https://codesandbox.io). Codesandbox, with its state and effects complexity, benefits greatly combining Overmind and Typescript.


# Introduction

In this introduction you will get an overview of Overmind and how you can think about application development. We will be using [REACT](https://reactjs.org/) to write the UI, but you can use Overmind with [VUE](https://vuejs.org/) and [ANGULAR](https://angular.io/) if either of those is your preference.

{% hint style="info" %}
If you rather want to go right ahead and set up a local project, please have a look at the [QUICKSTART](/master-1/quickstart) guide.
{% endhint %}

Before we move on, have a quick look at this sandbox. It is a simple counter application and it gives you some foundation before talking more about Overmind and building applications.

{% embed url="<https://codesandbox.io/s/overmind-counter-c4tuh?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

## Application state VS Component state

First of all we have to talk about **application** and **component** state. In the counter example above we chose to define our **count** state as application state, outside of the component. We could have defined the count inside the component instead and the application would work exactly the same. So why did we choose application state?

If the count example above was the entire application it would not make any sense to introduce application state and Overmind. But if you were to increase the scope of this simple application you would be surprised how quickly you get into the following scenarios:

1. **You want to introduce an other component that needs to know about the current state of the count.** This new component can not be a parent of the component owning the count state. It can not be a sibling either. It has to be a child. If it is not an immediate child the count state has to be passed down the component tree until it reaches your new component.
2. **You want to remember the count, even though it is not shown in the UI**. Your count is behind one of multiple tabs in the UI. When the user changes the tabs you do not want the count to reset. The only way to ensure this is to move the count state up to a parent component that is no longer a child of the tab and then pass the count state back down again.
3. **You want to change the count from a side effect**. You have a websocket connection which changes the count when a message is received. If you want to avoid this websocket connection to open and close as the component mounts and unmounts you will have to move the websocket connection up the component tree.
4. **You want to change the count as part of multiple changes**. When you click the increase count button you need to change both the count state and an other state related to a different part of the UI. To be able to change both states at the same time, they have to live inside the same component, which has to be a parent of both components using the state.

Introducing these scenarios we said: **You want**. In reality we rarely know exactly what we want. We do not know how our state and components will evolve. And this is the most important point. By using application state instead of component state you get flexibility to manage whatever comes down the road without having to refactor wrong assumptions.

**So is component state bad?** No, certainly not. You do not want to overload your application state with state that could just as well have been inside a component. The tricky thing is to figure out when that is absolutely the case. For example:

1. **Modals should certainly be component state?** Not all modals are triggered by a user interaction. A profile modal might be triggered by clicking a profile picture, but also open up when a user opens the application and is missing information.
2. **The active tab should certainly be component state?** The active tab might be part of the url query, `/user?tab=count`. That means it should rather be a hyperlink where your application handles the routing and provides state to identify the active tab.
3. **Inputs should certainly be component state?** If the input is part of an application flow, you might want to empty out the content of that input related to other changes, or even change it to something else.

How you want to go about this is totally up to you. We are not telling you exactly how to separate application and component state. What we can tell you though; **“If you lean towards application state you are more flexible to future changes”**.

## Defining state

As you can see in the count example we added a state object when we created the instance.

```javascript
createOvermind({
  state: {
    count: 0
  },
  ...
})
```

This state object will hold all the application state, we call it a *single state tree*. That does not mean you define all the state in one file and we will talk more about that later. For now let us talk about what you put into this state tree.

A single state tree typically favours serializable state. That means state that can be `JSON.parse` and `JSON.stringify` back and forth. It can be safely passed between the client and the server, localStorage or to web workers. You will use **strings**, **numbers**, **booleans**, **arrays**, **objects** and **null**. Overmind also has the ability to allow you define state values as class instances, even serializing back and forth. You can read more about that in [State](/master-1/core/defining-state).

## Defining actions

When you need to change your state you define actions. Overmind only allows changing the state of the application inside the actions. An error will be thrown if you try to change the state inside a component. The actions are plain functions/methods. The only thing that makes them special is that they all receive a preset first argument, called **the context**:

```javascript
createOvermind({
  state: {
    count: 0
  },
  actions: {
    increaseCount({ state }) {
      state.count++;
    },
    decreaseCount({ state }) {
      state.count--;
    }
  }
})
```

Here we can see that we [DESTRUCTURE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) the context to grab the **state**. You can also access other actions on the context:

```javascript
createOvermind({
  state: {
    count: 0
  },
  actions: {
    increaseCount({ state, actions }) {
      state.count++;
      actions.decreaseCount()
    },
    decreaseCount({ state }) {
      state.count--;
    }
  }
})
```

And as we will see later you will also be using **effects** from the context.

## Increasing complexity

Now we will move to a more complex example. Please have a look:

{% embed url="<https://codesandbox.io/s/overmind-todomvc-simple-097zs?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

We have now separated out the Overmind related logic into its own file, **app.js**. This file creates the Overmind instance and also exports how the components will interact with the state and the actions, the hook called **useApp**. Vue and Angular has other mechanisms conventional to those frameworks where application state and actions can be accessed.

## References

What to take notice of is how we store the **todos** of this application.

```javascript
createOvermind({
  state: {
    ...
    todos: {},
    ...
  },
  ...
})
```

It is just an empty object. You might intuitively think of a list of todos as an array. Not blaming you, it makes total sense. That said, when you work with entities that has a unique identifier, typically an *id* property, you are better off storing them in an object. Each key in this object will be the unique identifier of a todo. For example:

```javascript
{
  'todo-1': {
    id: 'todo-1',
    title: 'My Todo',
    completed: false
  },
  'todo-2': {
    id: 'todo-2',
    title: 'My Other Todo',
    completed: true
  },
}
```

When you need to reference a todo, for example a component wants to reference a todo to toggle its completed state or maybe delete one, you will pass “todo-1” or “todo-2” as a reference instead of the todo itself.

Working with references this way avoids logic where you need to **find** a todo in an array or **filter**/**splice** out a todo to delete it from an array. You simply just point to the todos state to grab or delete it:

```javascript
state.todos[myReference]

delete state.todos[myReference]
```

Using references also ensures that only one instance of any todo will live in your state tree. The todo itself lives on the **todos** state, while everything else in the state tree references a todo by using its id. For example our **editingTodoId** state uses the id of a todo to reference which todo is currently being edited.

## Deriving state

Looking through the example you have probably noticed these:

```javascript
createOvermind({
  state: {
    ...,
    currentTodos: derived(({ todos, filter }) => {
      return Object.values(todos).filter(todo => {
        switch (filter) {
          case 'active':
            return !todo.completed;
          case 'completed':
            return todo.completed;
          default:
            return true;
        }
      });
    }),
    activeTodoCount: derived(({ todos }) => {
      return Object.values(todos).filter(todo => !todo.completed).length;
    }),
    hasCompletedTodos: derived(({ todos }) => {
      return Object.values(todos).some(todo => todo.completed);
    }),
    isAllTodosChecked: derived(({ currentTodos }) => {
      return currentTodos.every(todo => todo.completed);
    }),
  },
  ...
})
```

Our state tree is concerned with state values that you will change using actions. But you can also automatically produce state values based on existing state. An example of this would be to list the **currentTodos**. It uses the todos and filter state to figure out what todos to actually display. Sometimes this is called computed state. We call it **derived** state.

By using the **derived** function exported from Overmind you can insert a function into the state tree. These functions receives a preset first argument which is the immediate state, the state object the derived is attached to. In bigger applications you might also need to use the second argument, which is the root state of the application. The derived will automatically track whatever state you use and then flag itself as dirty whenever it changes. If derived state is used while being dirty, the function will run again. If it is not dirty, a cached value is returned.

## Effects

Now let us move into an even more complex application. Here we have added **effects**. Specifically effects to handle routing, storing todos to local storage and producing unique ids for the todos. We have added an **onInitialize** hook which is a special function Overmind runs when the application starts.

{% embed url="<https://codesandbox.io/s/overmind-todomvc-2im6p?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

You can think of effects as a contract between your application and the outside world. You write an effect API of **what** your application needs and some 3rd party tool or native JavaScript API will implement **how** to provide it. Let us look at the router:

```javascript
createOvermind({
  ...,
  effects: {
    ...,
    router: {
      initialize(routes) {
        Object.keys(routes).forEach(url => {
          page(url, ({ params }) => routes[url](params));
        });
        page.start();
      },
      goTo(url) {
        page.show(url);
      },
    },
  }
})
```

The router uses the [PAGE](https://www.npmjs.com/package/page) tool to manage routing. It takes a “url to action” option that makes sense for this application, but you could define this however you wanted.

```javascript
effects.router.initialize({
  '/': () => actions.changeFilter('all'),
  '/active': () => actions.changeFilter('active'),
  '/completed': () => actions.changeFilter('completed'),
});
```

This argument passed is transformed into something Page can understand. What this means is that we can easily switch out Page with some other tool later if we wanted to, or maybe if the app ran in different environments you could change out the implementation of the router dynamically. We were also able to combine **page** and **page.start** behind one method, which cleans up our application code. We did the same for the **storage** effect. We use localStorage and JSON.parse/JSON.stringify behind a single method.

## Scaling up the application

Defining all the state, actions and effects on one object would not work very well for a large application. A convention in Overmind is to split these concepts into different files behind folders representing a domain of the application. In this next sandbox you can see how we split up state, actions and effects into different files. They are all exposed through a main file representing that domain, in this case “the root domain”:

{% embed url="<https://codesandbox.io/s/overmind-todomvc-split-xdh41?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

Also notice that we have split up the instantiation of Overmind from the definition of the application. What this allows us to do is reuse the same application configuration for testing purposes and/or server side rendering. We separate the definition from the instantiation.

To scale up your code even more you can split it into **namespaces**. You can read more about that in the [STRUCTURING THE APP](/master-1/core/structuring-the-app) guide.

## Get to know Typescript

Now that we have insight into the building blocks of Overmind it is time to introduce typing. If you are already familiar with [TYPESCRIPT](https://www.typescriptlang.org/) you will certainly enjoy the minimal typing required to get full type safety across your application. If you are unfamiliar with Typescript Overmind is a great project to start using it, for the very same reason.

Have a look at this new project where we have typed the application:

{% hint style="info" %}
You have to **OPEN SANDBOX** to get the full Typescript experience.
{% endhint %}

{% embed url="<https://codesandbox.io/s/overmind-todomvc-typescript-39h7y?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

As you can see we only have to add an **Action** type to our functions and optionally give it an input type. This is enough for the action to give you all information about the application. Try changing some code and even add some code to see how Typescript helps you to explore the application and ensure that you implement new functionality correctly.

If you go to the **state.ts** file and change the type:

```typescript
export type State = {
  ...,
  newTodoTitle: string
  ...
}
```

to:

```typescript
export type State = {
  ...,
  todoTitle: string
  ...
}
```

You can now visit the **actions.ts** file and the **AddTodo.tsx** component. As you can see Typescript yells because the typing is now wrong. This is very powerful in complex projects which moves fast. The reason being that you can safely rename and refactor without worrying about breaking the code.

To learn more about Overmind and Typescript read the [TYPESCRIPT](https://www.overmindjs.org/guides/beginner/05_typescript) documentation.

## Development tool

Overmind also ships with its own development tool. It can be installed as a [VSCODE PLUGIN](https://marketplace.visualstudio.com/items?itemName=christianalfoni.overmind-devtools-vscode) or installed as an NPM package. The development tool knows everything about what is happening inside the application. It shows you all the state, running actions and connected components. By default Overmind connects automatically to the devtool if it is running.

Open the **sandbox** above and try by going to the **index.tsx** file and change:

```typescript
export const overmind = createOvermind(config, {
  devtools: false,
});
```

to:

```typescript
export const overmind = createOvermind(config, {
  devtools: true,
});
```

Go to your terminal and use the NPM executor to instantly fire up the development tool.

```
npx overmind-devtools@latest
```

Refresh the sandbox preview and you should see the devtools populated with information from the application.

{% hint style="info" %}
This only works in **CHROME** when running on codesandbox.io, due to domain security restrictions. It works on all browsers when running your project locally.
{% endhint %}

![](/files/-Ly_Ye8-PCJwaz9lUhuJ)

Here we get an overview of the current state of the application, including our derived state. If we move to the next tab we get an overview of the execution. We have not triggered any actions yet, but our **onInitialized** hook has run and triggered some logic.

![](/files/-Ly_YjTVWjycuO_dIxXo)

Here we can see that we grabbing todos from local storage and initializing our router. We can also see that the router instantly fires off our **changeFilter** action causing a state change on the filter. At the end we can see that our reaction triggered, saving the todos.

{% hint style="info" %}
You might wonder why the reaction triggered when it was defined after we changed the **todos** state. Overmind batches up changes to state and *flushes* at optimal points in the execution. For example when an action ends or some asynchronous code starts running. The reaction reacts to these flushes, just like components do.
{% endhint %}

Moving on we also get insight into components looking at our application state:

![](/files/-Ly_Yxpz7Z9HxOvpv-nB)

Currently two components are active in the application and we can also see what state they are looking at.

A chronological list of all state changes and effects run is available on the next tab. This can be useful with asynchronous code where actions changes state “in between” each other.

![](/files/-Ly_Z1fI66LDL5MCNQkc)

Now, let us try to add a new todo and see what happens.

![](/files/-Ly_Z7j6WSVu9swkIksn)

Our todo has been added and we can even see how the derived state was affected by this change. Looking at our actions tab we can see what state changes were performed and by hovering the mouse on the yellow label up right you get information about what components and derived were affected by state changes in this action.

![](/files/-Ly_ZE0yRYU9_L71s3WK)

## Managing complexity

![](/files/-M97Z2d6djobVLSbpSZJ)

Overmind gives you a basic foundation with its **state**, **actions** and **effects**. As mentioned previously you can split these up into multiple namespaces to organize your code. This manages the complexity of scaling. There is also a complexity of reusability and managing execution over time. The **operators** API allows you to split your logic into many different composable parts. With operators like **debounce**, **waitUntil** etc. you are able to manage execution over time. With the latest addition of **statemachines** you have the possiblity to manage the complexity of state and interaction. What interactions should be allowed in what states. And with state values as **class instances** you are able to co-locate state with logic.

The great thing about Overmind is that none of these concepts are forced upon you. If you want to build your entire app in the root namespace, only using actions, that is perfectly fine. You want to bring in operators for a single action to manage time complexity, do that. Or do you have a concept where you want to safely control what actions can run in certain states, use a statemachines. Overmind just gives you tools, it is up to you to determine if they are needed or not.

## Moving from here

We hope this introduction got you excited about developing applications and working with Overmind. From this point you can continue working with [CODESANDBOX.IO](https://codesandbox.io/) or set up a local development flow. It is highly encouraged to use Overmind with Typescript, it does not get any more complex than what you see in this simple TodoMvc application.

Move over to the [QUICKSTART](/master-1/quickstart) to get help setting up your project. The other guides will give you a deeper understanding of how Overmind works. If you are lost please talk to us on [DISCORD](https://discord.gg/YKw9Kd) and we are happy to help. And yeah… have fun! :-)


# Quickstart

From the command line install the Overmind package:

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

```
npm install overmind overmind-react
```

{% endtab %}

{% tab title="Vue" %}

```
npm install overmind overmind-vue
```

{% endtab %}

{% tab title="Angular" %}

```
npm install overmind overmind-angular
```

{% endtab %}
{% endtabs %}

### Setup

Now set up a simple application like this:

{% tabs %}
{% tab title="overmind/state.js" %}

```javascript
export const state = {
  title: 'My App'
}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

And fire up your application in the browser or whatever environment your user interface is to be consumed in by the users.

Move on with the specific view layer of choice to connect your app:

[**REACT** ](/master-1/views/react)**-** [**ANGULAR**](/master-1/views/angular) **-** [**VUE**](/master-1/views/vue)


# How to learn

To learn any new tool it is important to have some goal unrelated to the tool itself. Maybe you have a pet project or a project at work you want to try it on. There is a lot on the menu on the left here, so let us give you some pointers to the most important docs to understand Overmind.

* [**The introduction video**](https://youtu.be/82Aq_ujnBQw) gives you a quick overview of what Overmind is
* You will benefit from getting into the overall structure with [**Configuration**](/master-1/core/structuring-the-app)**,** then moving on to the specific concepts of [**State**](/master-1/core/defining-state)**,** [**Actions**](/master-1/core/writing-application-logic) and [**Effects**](/master-1/core/running-side-effects)
* If you use Typescript it can be a good idea to already now explore how you use Overmind with [**Typescript**](/master-1/core/typescript)
* Ready to start building something? Check of the view packages for [**React**](/master-1/views/react), [**Angular**](/master-1/views/angular) or [**Vue**](/master-1/views/vue), to get you started
* Once you got a feel for it, the **Connecting components** guide will give you some more insight into how you use your state in the components
* From here it is totally up to you! Good luck and please visit our Discord channel for support


# Videos

## Overmind introduction

{% embed url="<https://youtu.be/82Aq_ujnBQw>" %}

## Devtools introduction

{% embed url="<https://youtu.be/j_dzXucq3E4>" %}

## Replacing Vuex with Overmind

{% embed url="<https://youtu.be/O5FMIXwYLAA>" %}

## VSCode extension

{% embed url="<https://youtu.be/P4CwiC0f56Y>" %}


# FAQ

## The devtool is not responding?

First… try to refresh your app to reconnect. If this does not work make sure that the entry point in your application is actually creating an instance of Overmind. The code **createOvermind(config)** has to run to instantiate the devtools.

This is also a common misconception about the ports. You want `createOvermind` to connect to the port defined inside the Devtool, which is `3031` by default.

## The devtools does not open in VS Code?

Restart VS Code

## My operator actions are not running?

Operators are identified with a Symbol. If you happen to use Overmind across packages you might be running two versions of Overmind. The same goes for core package and view package installed out of version sync. Make sure you are only running on package of Overmind by looking into your **node\_modules** folder.


# Devtools

## Standalone app

You can start the devtools by using the NPM executor:

```javascript
npx overmind-devtools@latest
```

{% hint style="info" %}
Adding **@latest** just ensures that you break any caching, meaning you will always run the latest version
{% endhint %}

You can also install the devtools with your project, allowing you to lock a specific version of the devtools to your project:

```javascript
npm install overmind-devtools
```

With the package [CONCURRENTLY](https://www.npmjs.com/package/concurrently) you can start the devtools as you start your build process:

```
npm install overmind-devtools concurrently
```

{% code title="package.json" %}

```javascript
{
  ...
  "scripts": {
    "start": "concurrently \"overmind-devtools\" \"someBuildTool\""
  },
  ...
}
```

{% endcode %}

## VS Code

You can also install the [OVERMIND DEVTOOLS](https://marketplace.visualstudio.com/items?itemName=christianalfoni.overmind-devtools-vscode) extension. This will allow you to work on your application without leaving the IDE at all.

![](/files/-Ly_HBec6C-YihjahYdA)

{% hint style="info" %}
If you are using the **Insiders** version of VSCode the extension will not work. It seems to be some extra security setting.
{% endhint %}

## Connecting from the application

When you create your application it will automatically connect through **localhost:3031**, meaning that everything should just work out of the box. If you need to change the port, connect the application over a network (mobile development) or similar, you can configure how the application connects:

```javascript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config, {
  devtools: '10.0.0.1:3031'
})
```

### Connecting on Chromebook

ChromeOS does not expose localhost as normal. That means you need to connect with **penguin.termina.linux.test:3031**, or you can use the following plugin to forward **localhost:**

{% embed url="<https://chrome.google.com/webstore/detail/connection-forwarder/ahaijnonphgkgnkbklchdhclailflinn/related?hl=en-US>" %}

## Hot Module Replacement

A popular concept introduced by Webpack is [HMR](https://webpack.js.org/concepts/hot-module-replacement/). It allows you to make changes to your code without having to refresh. Overmind automatically supports HMR. That means when **HMR** is activated Overmind will make sure it updates and manages its state, actions and effects. Even the devtools will be updated as you make changes.

Typically you add this, here showing with React:

```typescript
import React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import { App } from './components/App'


const overmind = createOvermind(config)

render(<Provider value={overmind}><App /></Provider>, document.querySelector('#app'))

// Allows this module to run again without refresh,
// meaning "createOvermind" runs again and automatically
// reconfigures
if (module.hot) {
  module.hot.accept()
}
```

Though you can also manually only update Overmind by:

{% tabs %}
{% tab title="index.js" %}

```typescript
import React from 'react'
import { render } from 'react-dom'
import { overmind } from './overmindInstance'
import { Provider } from 'overmind-react'
import { App } from './components/App'

render(<Provider value={overmind}><App /></Provider>, document.querySelector('#app'))
```

{% endtab %}

{% tab title="overmindInstance.js" %}

```javascript
import { createOvermind } from 'overmind'
import { config } from './overmind'

export const overmind = createOvermind(config)

// When this module runs again "createOvermind" is run
// and it automatically reconfigures
if (module.hot) {
  module.hot.accept()
}
```

{% endtab %}
{% endtabs %}


# Configuration

Overmind is based on a core concept of:

`{ state, actions, effects }`

This data structure is called **the configuration** of your application. If it is a simple application you might have a single configuration, but typically you will create multiple of them and use tools to merge them together into one big configuration. But before we look at the scalability of Overmind, let’s talk about file structure.

## Namspaces

![](/files/-M97Z26X8vn4YQyPL48q)

As your application grows you start to separate it into different namespaces. A namespace might be closely related to a page in your application, or maybe it is strictly related to managing some piece of data. It does not matter. You define the namespaces of your application and they probably change over time as well. What matters in the context of Overmind though is that each of these namespaces will contain their own state, actions and effects. So imagine a file structure of:

```
overmind/
  state.ts
  actions.ts
  effects.ts
  index.ts
```

In this structure we are splitting up the different components of the configuration. This is a good first step. The **index** file acts as the file that brings the **state**, **actions** and **effects** together.

But if we want to split up into actual namespaces it would look more like this:

```
overmind/
  posts/
    state.ts
    actions.ts
    effects.ts
    index.ts
  admin/
    state.ts
    actions.ts
    effects.ts
    index.ts
  index.ts
```

In this case each namespace **index** file bring its own state, actions and effects together and the **overmind/index** file is responsible for bringing the whole configuration together.

## The state file

You will typically define your **state** file by exporting a single constant named *state*.

{% tabs %}
{% tab title="overmind/posts/state.js" %}

```typescript
export const state = {
  posts: []
}
```

{% endtab %}

{% tab title="overmind/admin/state.js" %}

```typescript
export const state: State = {
  users: []
}
```

{% endtab %}
{% endtabs %}

## The actions file

The actions are exported individually by giving them a name and a definition.

{% tabs %}
{% tab title="overmind/posts/actions.js" %}

```typescript
export const getPosts = async () => {}

export const addNewPost = async () => {}
```

{% endtab %}

{% tab title="overmind/admin/actions.js" %}

```typescript
export const getUsers = async () => {}

export const changeUserAccess = async () => {}
```

{% endtab %}
{% endtabs %}

## The effects file

The effects are also exported individually where you would typically organize the methods in an object, but this could have been a class instance or just a plain function as well.

{% tabs %}
{% tab title="overmind/posts/effects.js" %}

```typescript
export const postsApi = {
  getPostsFromServer() {}
}
```

{% endtab %}

{% tab title="overmind/admin/effects.js" %}

```typescript
export const adminApi = {
  getUsersFromServer() {}
}
```

{% endtab %}
{% endtabs %}

You might find it more useful to define a single effects file at the root of your application and rather create a file for each effect.

{% tabs %}
{% tab title="overmind/effects/index.js" %}

```typescript
import * as api from './api'

export {
  api
}
```

{% endtab %}

{% tab title="overmind/effects/api.js" %}

```typescript
export const getUser = async () => {}

export const getPosts = async () => {}
```

{% endtab %}
{% endtabs %}

## Bring it together

Now let us export the state, actions and effects for each module and bring it all together into a **namespaced** configuration.

{% tabs %}
{% tab title="overmind/posts/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export {
  state,
  actions,
  effects
}
```

{% endtab %}

{% tab title="overmind/admin/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export {
  state,
  actions,
  effects
}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { namespaced } from 'overmind/config'
import * as posts from './posts'
import * as admin from './admin'

export const config = namespaced({
  posts,
  admin
})
```

{% endtab %}
{% endtabs %}

We used the **namespaced** function to put the state, actions and effects from each namespace behind a key. In this case the key is the same as the name of the namespace itself. This is an effective way to split up your app.

You can also combine this with the **merge** tool to have a top level namespace.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { merge, namespaced } from 'overmind/config'
import { state } from './state'
import * as posts from './posts'
import * as admin from './admin'

export const config = merge(
  {
    state
  },
  namespaced({
    posts,
    admin
  })
)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Even though you split up into different namespaces each namespace has access to the state, actions and effects of the whole application. This is an important feature of Overmind which allows you to scale up and explore the domains of the application without having to worry about isolation.
{% endhint %}


# State

Typically we think of the user interface as the application itself. But the user interface is really just there to allow a user to interact with the application. This interface can be anything. A browser window, native, sensors etc. It does not matter what the interface is, the application is still the same.

The mechanism of communicating from the application to the user interface is called **state**. A user interface is created by **transforming** the current state. To communicate from the user interface to the application an API is exposed, called **actions** in Overmind. Any interaction can trigger an action which changes the state, causing the application to notify the user interface about any updated state.

![](/files/-Ly__8wUlT2Mz5acMDgQ)

## State tree

Overmind is structured as a single state tree. That means all of your state can be accessed through a single object, called the **state**. This state tree will hold values which describes different states of your application. The tree branches out using plain objects, which can be considered **branches** of your state tree.

```javascript
{ // branch
  modes: ['issues', 'admin'],
  currentModeIndex: 0,
  admin: { // branch
    currentUserId: null,
    users: { // branch
      isLoading: false,
      data: {},
      error: null
    },
  },
  issues: { // branch
    sortBy: 'name',
    isLoading: false,
    data: {},
    error: null
  }
}
```

## State tree values

The following are values to be used with the state tree.

### Objects

The plain objects are what **branches** out the tree. It is not really considered a value in itself, it is a state branch holding values.

### Arrays

Arrays are similar to objects in the sense that they hold other values, but instead of keys pointing to values you have indexes. That means it is ideal for iteration. But more often than not objects are actually better at managing lists of values. We can actually do fine without arrays in our state. It is when we produce the actual user interface that we usually want arrays. You can learn more about this in the [MANAGING LISTS](/master-1/guides-1/managing-lists) guide.

### Strings

Strings are of course used to represent text values. Names, descriptions and whatnot. But strings are also used for ids, types, etc. Strings can be used as values to reference other values. This is an important part in structuring state. For example in our **objects** example above we chose to use an array to represent the modes, using an index to point to the current mode, but we could also do:

```javascript
{
  modes: {
    issues: 0,
    admin: 1 
  },
  currentMode: 'issues'
  ...
}
```

Now we are referencing the current mode with a string. In this scenario you would probably stick with the array, but it is important to highlight that objects allow you to reference things by string, while arrays reference by number.

### Numbers

Numbers of course represent things like counts, age, etc. But just like strings, they can also represent a reference to something in a list. Like we saw in our **objects** example, to define what the current mode of our application is, we can use a number. You could say that referencing things by number works very well when the value behind the number does not change. Our modes will most likely not change and that is why an array and referencing the current mode by number, is perfectly fine.

### Booleans

Are things loading or not, is the user logged in or not? These are typical uses of boolean values. We use booleans to express that something is activated or not. We should not confuse this with **null**, which means “not existing”. We should not use **null** in place of a boolean value. We have to use either `true` or `false`.

### Null

All values, with the exception of booleans, can also be **null**. Non-existing. You can have a non-existing object, array, string or number. It means that if we haven’t selected a mode, both the string version and number version would have the value **null**.

### Derived

When you need to derive state you can add a derived function to your tree. Overmind treats these functions like a **getter**, but the returned value is cached and they can also access the root state of the application. A simple example of this would be:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
import { derived } from 'overmind'

export const state = {
  title: 'My awesome title',
  upperTitle: derived(state => state.title.toUpperCase())
}
```

{% endtab %}
{% endtabs %}

The first argument of the function is the state the derived function is attached to. A second argument is also passed and that is the root state of the application, allowing you to access whatever you would need.

{% hint style="info" %}
Even though derived state is defined as functions you consume them as plain values. You do not have to call the derived function to get the value. Derived functions can also be dynamically added.
{% endhint %}

You can also return a function from the derived. For example:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
import { derived } from 'overmind'

export const state = {
  users: {},
  getUserById: derived(state => id => state.users[id])
}
```

{% endtab %}
{% endtabs %}

The returned value here is indeed a function you call. The cool thing is that the function itself will never change, but whatever state you access when calling the function will be tracked by the caller of the function. So for example if a component uses **getUserById** during rendering it will track what is accessed in the function and continue tracking whatever you access on the returned value.

{% hint style="info" %}
You may use a derived for all sorts of calculations. But sometimes it's better to just use a plain action to manipulate some state than using a derived. Why? Imagine a table component having a lot of rows and columns. We assume the table component also takes care of sorting and filtering and is capable of adding new rows. Now if you solve the sorting and filtering using a derived the following could happen: User adds a new row but it is not displayed in the list because the derived immediately kicked in and filtered it out. Thats not a good user experience. Also in this case the filtering and sorting is clearly started by a simple user interaction (setting a filter value, clicking on a column,...) so why not just start an action which creates the new list of sorted and filtered keys? Also the heavy calculation is now very predictable and doesn't cause performance issues because the derived kickes in too often (Because it could have many dependencies you might didn't think of)
{% endhint %}

### Class instances

Overmind also supports using class instances as state values. Depending on your preference this can be a powerful tool to organize your logic. What classes provide is a way to co locate state and logic for changing and deriving that state. In functional programming the state and the logic is separated and it can be difficult to find a good way to organize the logic operating on that state.

It can be a good idea to think about your classes as models. They model some state.

{% tabs %}
{% tab title="overmind/models.js" %}

```javascript
class LoginForm {
  constructor() {
    this.username = ''
    this.password = ''
  }
  get isValid() {
    return Boolean(this.username && this.password)
  }
  reset() {
    this.username = ''
    this.password = ''
  }
}
```

{% endtab %}

{% tab title="overmind/state.js" %}

```javascript
import { LoginForm } from './models'

export const state = {
  loginForm: new LoginForm()
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
It is import that you do **NOT** use arrow functions on your methods. The reason is that this binds the context of the method to the instance itself, meaning that Overmind is unable to proxy access and track mutations
{% endhint %}

You can now use this instance as normal and of course create new ones.

#### Serializing class values

If you have an application that needs to serialize the state, for example to local storage or server side rendering, you can still use class instances with Overmind. By default you really do not have to do anything, but if you use **Typescript** or you choose to use **toJSON** on your classesOvermind exposes a symbol called **SERIALIZE** that you can attach to your class.

```typescript
import { SERIALIZE } from 'overmind'

class User {
  constructor() {
    this.username = ''
    this.jwt = ''
  }
  toJSON() {
    return {
      [SERIALIZE]: true,
      username: this.username
    }
  }
}
```

If you use **Typescript** you want to add **SERIALIZE** to the class itself as this will give you type safety when rehydrating the state.

```typescript
import { SERIALIZE } from 'overmind'

class User {
  [SERIALIZE] = true
  username = ''
  jwt = ''
}
```

{% hint style="info" %}
The **SERIALIZE** symbol will not be part of the actual serialization done with **JSON.stringify**
{% endhint %}

#### Rehydrating classes

The [**rehydrate**](/master-1/api-1/rehydrate) \_\*\*\_utility of Overmind allows you to rehydrate state either by a list of mutations or a state object, like the following:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(state, {
    user: {
      username: 'jenny',
      jwt: '123'
    }
  })    
}
```

{% endtab %}
{% endtabs %}

Since our user is a class instance we can tell rehydrate what to do, where it is typical to give the class a static **fromJSON** method:

{% tabs %}
{% tab title="overmind/models.js" %}

```typescript
import { SERIALIZE } from 'overmind'

class User {
  [SERIALIZE]
  constructor() {
    this.username = ''
    this.jwt = ''
  }
  static fromJSON(json) {
    return Object.assign(new User(), json)
  }
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(
    state,
    {
      user: {
        username: 'jenny',
        jwt: '123'
      }
    },
    {
      user: User.fromJSON
    }
  )    
}
```

{% endtab %}
{% endtabs %}

It does not matter if the state value is a class instance, an array of class instances or a dictionary of class instances, rehydrate will understand it.

That means the following will behave as expected:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
import { User } from './models'

export const state = {
  user: null, // Can be existing class instance or null
  usersList: [], // Expecting an array of values
  usersDictionary: {} // Expecting a dictionary of values
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(
    state,
    {
      user: {
        username: 'jenny',
        jwt: '123'
      },
      usersList: [{...}, {...}],
      usersDictionary: {
        'jenny': {...},
        'bob': {...}
      }
    },
    {
      user: User.fromJSON,
      usersList: User.fromJSON,
      usersDictionary: User.fromJSON
    }
  )    
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that **rehydrate** gives you full type safety when adding the **SERIALIZE** symbol to your classes. This is a huge benefit as Typescript will yell at you when the state structure changes, related to the rehydration
{% endhint %}

### Statemachines

Very often you get into a situation where you define states as **isLoading**, **hasError** etc. Having these kinds of state can cause **impossible states**. For example:

```typescript
const state = {
  isAuthenticated: true,
  isAuthenticating: true
}
```

You can not be authenticating and be authenticated at the same time. This kind of logic very often causes bugs in applications. That is why Overmind allows you to define statemachines. It sounds complicated, but is actually very simple.

To properly understand state machines, please read the guide [**Using state machines**](/master-1/guides-1/using-state-machines).

## References

When you add objects and arrays to your state tree, they are labeled with an “address” in the tree. That means if you try to add the same object or array in multiple spots in the tree you will get an error, as they can not have multiple addresses. Typically this indicates that you’d rather want to create a reference to an existing object or array.

So this is an example of how you would **not** want to do it:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  users: {},
  currentUser: null
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
export const setUser = ({ state }, id) => {
  state.currentUser = state.users[id]
}
```

{% endtab %}
{% endtabs %}

You’d rather have a reference to the user id, and for example use a **getter** to grab the actual user:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  users: {},
  currentUserId: null,
  get currentUser(this) {
    return this.users[this.currentUserId]
  } 
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
export const setUser = ({ state }, id) => {
  state.currentUserId = id
}
```

{% endtab %}
{% endtabs %}

## Exposing the state

We define the state of the application in **state** files. For example, the top level state could be defined as:

{% tabs %}
{% tab title="overmind/state.js" %}

```javascript
export const state = {
  isLoading: false,
  user: null
}
```

{% endtab %}
{% endtabs %}

To expose the state on the instance you can follow this recommended pattern:

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
For scalability you can define **namespaces** for multiple configurations. Read more about that in [Structuring the app](/master-1/core/structuring-the-app)
{% endhint %}

## Summary

This short guide gave you some insight into how we think about state and what state really is in an application. There is more to learn about these values and how to use them to describe the application. Please move on to other guides to learn more.


# Actions

Overmind has a concept of an **action**. An action is just a function where the first argument is injected. This first argument is called the **context** and it holds the state of the application, whatever effects you have defined and references to the other actions.

You define actions under the **actions** key of your application configuration.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction = (context) => {

}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import * as actions from './actions'

export const config = {
  actions
}
```

{% endtab %}
{% endtabs %}

## Using the context

The context has three parts: **state**, **effects** and **actions**. Typically you destructure the context to access these pieces directly:

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const myAction = ({ state, effects, actions }) => {

}
```

{% endtab %}
{% endtabs %}

When you point to either of these you will always point to the “top of the application. That means if you use namespaces or other nested structures the context is always the root context of the application.

{% hint style="info" %}
The reason Overmind only has a root context is because having isolated contexts/domains creates more harm than good. Specifically when you develop your application it is very difficult to know exactly how the domains of your application will look like and what state, actions and effects belong together. By only having a root context you can always point to any domain from any other domain allowing you to easily manage cross-domain logic, not having to refactor every time your domain model breaks.
{% endhint %}

## Passing values

When you call actions you can pass a single value. This value appears as the second argument, after the context.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction = ({ state, effects, actions }, value) => {

}
```

{% endtab %}
{% endtabs %}

When you call an action from an action you do so by using the **actions** passed on the context, as this is the evaluated action that can be called.

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const myAction = ({ state, effects, actions }) => {
  actions.myOtherAction('foo')
}

export const myOtherAction = ({ state, effects, actions }, value) {

}
```

{% endtab %}
{% endtabs %}

## Organizing actions

Some of your actions will be called from the outside, publicly, maybe from a component. Other actions are only used internally, either being passed to an effect or just holding some piece of logic you want to reuse.&#x20;

There are two conventions to choose from:

### Namespace

{% tabs %}
{% tab title="overmind/internalActions.js" %}

```typescript
export const internalActionA = ({ state, effects, actions }, value) {}

export const internalActionB = async ({ state, effects, actions }) {}
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Action } from 'overmind'
import * as internalActions from './internalActions'

export const internal = internalActions

export const myAction: Action = ({ state, effects, actions }) => {
  actions.internal.internalActionA('foo')
  actions.internal.internalActionB()
}
```

{% endtab %}
{% endtabs %}

### Underscore

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction: Action = ({ state, effects, actions }) => {
  actions.internal._internalActionA('foo')
  actions.internal._internalActionB()
}

export const _internalActionA = ({ state, effects, actions }, value) {}

export const _internalActionB = async ({ state, effects, actions }) {}
```

{% endtab %}
{% endtabs %}

## Summary

The action in Overmind is a powerful concept. It allows you to define and organize logic that always has access to the core components of your application. State, effects and actions.


# Effects

Developing applications is not only about managing state, but also managing side effects. A typical side effect would be an HTTP request or talking to localStorage. In Overmind we just call these **effects**. There are several reasons why you would want to use effects:

1. All the code in your actions will be domain specific, no low level generic APIs
2. Your actions will have less code and you avoid leaking out things like URLs, types etc.
3. You decouple the underlying tool from its usage, meaning that you can replace it at any time without changing your application logic
4. You can more easily expand the functionality of an effect. For example you want to introduce caching or a base URL to an HTTP effect
5. The devtool tracks its execution
6. If you write Overmind tests, you can easily mock them
7. You can lazy-load the effect, reducing the initial payload of the app

## Exposing an existing tool

Let us just expose the [AXIOS](https://github.com/axios/axios) library as an **http** effect.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
export { default as http } from 'axios'
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export const config = {
  state,
  actions,
  effects
}
```

{% endtab %}
{% endtabs %}

We are just exporting the existing library from our effects file and including it in the application config. Now Overmind is aware of an **http** effect. It can track it for debugging and all actions and operators will have it injected.

Let us put it to use in an action that grabs the current user of the application.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const loadApp = async ({ effects, state }) => {
  state.currentUser = await effects.http.get('/user')
}
```

{% endtab %}
{% endtabs %}

That was basically it. As you can see we are exposing some low level details like the http method used and the URL. Let us follow the encouraged way of doing things and create our own **api** effect.

## Specific API

It is highly encouraged that you avoid exposing tools with their generic APIs. Rather build your own APIs that are more closely related to the domain of your application. Maybe you have an endpoint for fetching the current user. Create that as an API for your app.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
import * as axios from 'axios'

export const api = {
  getCurrentUser() {
    return axios.get<User>('/user')
  }
}
```

{% endtab %}
{% endtabs %}

Now you can see how clean your application logic becomes:

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
export const loadApp = async ({ effects, state }) => {
  state.currentUser = await effects.api.getCurrentUser()
}
```

{% endtab %}
{% endtabs %}

## Initializing effects

It can be a good idea to not allow your side effects to initialize when they are defined. This makes sure that they do not leak into tests or server side rendering. For example if you want to use Firebase, instead of initializing the Firebase application immediately we rather do it behind an **initialize** method:

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import * as firebase from 'firebase'

// We use IIFE to hide the private "app" variable
export const api = (() => {
  let app

  return {
    initialize() {
      app = firebase.initializeApp(...)      
    },
    async getPosts() {
      const snapshot = await app.database().ref('/posts').once('value')

      return snapshot.val()
    }
  }
})()
```

{% endtab %}
{% endtabs %}

We are doing two things here:

1. We use an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) to create a scoped internal variable to be used for that specific effect
2. We have created an **initialize** method which we can call from the Overmind **onInitialize** action, which runs when the Overmind instance is created

Example of initializing the effect:

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ effects }) => {
  effects.api.initialize()
  state.posts = await effects.api.getPosts()
}
```

{% endtab %}
{% endtabs %}

## Effects and state

Typically you explicitly communicate with effects from actions, by calling methods. But sometimes you need effects to know about the state of the application, or maybe some internal state in the effect should be exposed on your application state. Again we can take advantage of an **initialize** method on the effect:

{% tabs %}
{% tab title="overmind/effects.js" %}

```javascript
// We use an IIFE to isolate some variables
export const socket = (() => {
  _options
  _ws
  return {
    initialize(options) {
      _options = options
      _ws = new WebSocket('ws://...')
      _ws.onclose = () => options.onStatusChange('close')
      _ws.onopen = () => options.onStatusChange('open')
      _ws.addEventListener(
        'message',
        (event) => options.onMessage(event.data)
      )
    },
    send(type, data) {
      _ws.postMessage({
        type,
        data,
        token: _options.getToken()
      })
    }
  }
})()
```

{% endtab %}

{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ state, effects, actions }) => {
  effects.socket.initialize({
    onMessage: actions.onMessage,
    onStatusChange: actions.onSocketStatusChange,
    getToken() {
      return state.token
    }
  })
}
```

{% endtab %}
{% endtabs %}

Here we are passing in actions that can be triggered by the effect to expose internal state and/or other information that you want to manage.

## Lazy effects

You can also lazily load your effects in the **initialize** method. Let us say we wanted to load Firebase and its API on demand, or maybe just split out the code to make our app start faster.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
export const api = (() => {
  let app

  return {
    async initialize() {
      const firebase = await import('firebase')

      app = firebase.initializeApp(...)
    },
    async getPosts() {
      const snapshot = await app.database().ref('/posts').once('value')

      return snapshot.val()
    }
  }
})()
```

{% endtab %}
{% endtabs %}

In our initialize() we would just have to wait for the initialization to finish before using the API:

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ effects }) => {
  await effects.api.initialize()
  state.posts = await effects.api.getPosts()
}
```

{% endtab %}
{% endtabs %}

We could have been even bolder here making our effect download its dependency related to using any of its methods. Imagine for example the **firebase** library downloading when you run a **login** method on the effect.

## Configurable effect

By defining a class we can improve testability, allow using environment variables and even change out the actual implementation.

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import axios from 'axios'

export class Api {
  private baseUrl
  private request
  constructor (baseUrl, request) {
    this.baseUrl = baseUrl
    this.request = request
  }
  getCurrentUser()  {
    return this.request.get(`${this.baseUrl}/user`)
  }
}

export const api = new Api(IS_PRODUCTION ? '/api/v1' : 'http://localhost:4321', axios)
```

{% endtab %}
{% endtabs %}

We export an instance of our **Api** to the application. This allows us to also create instances in isolation for testing purposes, making sure our Api class works as we expect.

## Summary

Importing side effects directly into your code should be considered bad practice. If you think about it from an application standpoint it is kinda weird that it runs HTTP verb methods with a URL string passed in. It is better to create an abstraction around it to make your code more consistent with the domain, and by doing so also improve maintainability.


# Operators

You get very far building your application with straightforward imperative actions. This is typically how we learn programming and is arguably close to how we think about the world. But this approach can cause you to overload your actions with imperative code, making them more difficult to read and especially reuse pieces of logic. As the complexity of your application increases you will find benefits to doing some of your logic, or maybe all your logic, in a functional style.

Let us look at a concrete example of how messy an imperative approach would be compared to a functional approach.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
let debounce
export const search = ({ state, effects }, event) => {
  state.query = event.currentTarget.value

  if (query.length < 3) return

  if (debounce) clearTimeout(debounce)

  debounce = setTimeout(async () => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false

    debounce = null
  }, 200)
}
```

{% endtab %}
{% endtabs %}

What we see here is an action trying to express a search. We only want to search when the length of the query is more than 2 characters and we only want to trigger the search when the user has not changed the query for 200 milliseconds.

If we were to do this in a functional style it would look more like this:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import { pipe, debounce, mutate, filter } from 'overmind'

export const search = pipe(
  mutate(({ state }, value) => {
    state.query = value
  }),
  filter(({ state }) => state.query.length > 2),
  debounce(200),
  mutate(({ state, effects }) => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false
  })
)
```

{% endtab %}
{% endtabs %}

As you can see our action is described more declaratively. We could have moved each individual piece of logic, each operator, into a different file. All these operators could now be reused in other action compositions.

## Structuring operators

You will typically rely on an **operators** file where all your composable pieces live. Inside your **actions** file you expose the operators and compose them together using **pipe** and other *composing* operators. This approach ensures:

1. Each operator is defined separately and in isolation
2. The action composed of operators is defined with the other actions
3. The action composed of operators is declarative (no inline operators with logic)

Let us look at how the operators in the search example could have been implemented:

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {filter, mutate } from 'overmind'

export const setQuery = () =>
  mutate(function setQuery({ state }, query) {
    state.query = query
  })

export const lengthGreaterThan = (length) =>
  filter(function lengthGreaterThan(_, value) {
    return value.length > length
  })

export const getSearchResult = () => 
  mutate(async function getSearchResult({ state, effects }, query) {
    state.isSearching = true
    state.searchResult = await effects.api.search(query)
    state.isSearching = false
  })
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that we give all the actual operator functions the same name as the exported variable that creates it. The reason is that this name is picked up by the devtools and gives you more insight into how your code runs.
{% endhint %}

You might wonder why we define the operators as functions that we call. We do that for the following reasons:

1. It ensures that each composition using the operator has a unique instance of that operator. For most operators this does not matter, but for others like **debounce** it actually matters.
2. Some operators require options, like the **lengthGreaterThan** operator we created above. Defining all operators as functions just makes things more consistent.
3. If you were to create an operator that is composed of other operators you can safely do so without thinking about the order of definition in the *operators* file. The reason being that the operator is lazily created
4. With Typescript it opens up to partial and generic typed operators. Read more about this in the [Typescript](/master-1/core/typescript) guide

Now, you might feel that we are just adding complexity here. An additional file with more syntax. But clean and maintainable code is not about less syntax. It is about structure, predictability and reusability. What we achieve with this functional approach is a super readable abstraction in our *actions* file. There is no logic there, just references to logic. In our *operators* file each piece of logic is defined in isolation with very little logic.

## Calling operators

You typically compose the different operators together with **pipe** and **parallel** in the *actions* file, but any operator can actually be exposed as an action. With the search example:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import {pipe, debounce, mutate, filter } from 'overmind'

export const search = pipe(
  mutate(({ state }, value) => {
    state.query = value
  }),
  filter(({ state }) => state.query.length > 2),
  debounce(200),
  mutate(({ state, effects }) => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false
  })
)
```

{% endtab %}
{% endtabs %}

You would call this action like any other:

```typescript
overmind.actions.search("something")
```

## Inputs and Outputs

To produce new values throughout your pipe you can use the **map** operator. It will put whatever value you return from it on the pipe for the next operator to consume.

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {map, mutate } from 'overmind'

export const toNumber = () =>
  map(function toNumber(_, value) { 
    return Number(value)
  })

export const setValue = () =>
  mutate(function setValue({ state}, value) {
    state.value = value
  })
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import {pipe } from 'overmind'
import * as o from './operators'

export const onValueChange = pipe(
  o.toNumber(),
  o.setValue()
)
```

{% endtab %}
{% endtabs %}

## Custom operators

The operators concept of Overmind is based on the [OP-OP SPEC](https://github.com/christianalfoni/op-op-spec), which allows for endless possibilities in functional composition. But since Overmind does not only pass values through these operators, but also the context where you can change state, run effects etc., we want to simplify how you can create your own operators. The added benefit of this is that the operators you create are also tracked in the devtools.

### toUpperCase <a href="#create-custom-operators-touppercase" id="create-custom-operators-touppercase"></a>

Let us create an operator that simply uppercases the string value passed through. This could easily have been done using the **map** operator, but for educational purposes let us see how we can create our very own operator.

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {createOperator, mutate } from 'overmind'

export const toUpperCase = () => {
  return createOperator('toUpperCase', '', (err, context, value, next) => {
    if (err) next(err, value)
    else next(null, value.toUpperCase())
  })
}

export const setTitle = mutate(({ state }, title) => {
  state.title = title
})
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { pipe } from 'overmind'
import { toUpperCase, setTitle } from './operators'

export const setUpperCaseTitle = pipe(
  toUpperCase(),
  setTitle
)
```

{% endtab %}
{% endtabs %}

We first create a function that returns an operator when we call it. We pass this operator a **name**, an optional **description** and the callback that is executed when the operator runs. This operator might receive an **error**, that you can handle if you want to. It also receives the **context**, the current **value** and a function called **next**.

In this example we did not use the **context** because we are not going to look at any state, run effects etc. We just wanted to change the value passed through. All operators need to handle the **error** in some way. In this case we just pass it along to the next operator by calling **next** with the error as the first argument and the current value as the second. When there is no error it means we can manage our value and we do so by calling **next** again, but passing **null** as the first argument, as there is no error. And the second argument is the new **value**.

### operations <a href="#create-custom-operators-operations" id="create-custom-operators-operations"></a>

You might want to run some logic related to your operator. Typically this is done by giving a callback. You can provide this callback whatever information you want, even handle its return value. So for example the **map** operator is implemented like this:

```typescript
import { createOperator } from 'overmind'

export function map(operation) {
  return createOperator(
    'map',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else next(null, operation(context, value))
    }
  )
}
```

### mutations <a href="#create-custom-operators-mutations" id="create-custom-operators-mutations"></a>

You can also create operators that have the ability to mutate the state, it is just a different factory **createMutationFactory**. This is how the **mutate** operator is implemented:

```typescript
import { createMutationOperator } from 'overmind'

export function mutate(operation) {
  return createMutationOperator(
    'mutate',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else {
        operation(context, value)
        next(null, value)
      }
    }
  )
}
```

### paths <a href="#create-custom-operators-paths" id="create-custom-operators-paths"></a>

You can even manage paths in your operator. This is how the **when** operator is implemented:

```typescript
import { createOperator } from 'overmind'

export function when(operation, paths) {
  return createOperator(
    'when',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else if (operation(context, value))
        next(null, value, {
          name: 'true',
          operator: paths.true,
        })
      else
        next(null, value, {
          name: 'false',
          operator: paths.false,
        })
    }
  )
}
```

### aborting <a href="#create-custom-operators-aborting" id="create-custom-operators-aborting"></a>

Some operators want to prevent further execution. That is also possible to implement, as seen here with the **filter** operator:

```typescript
import { createOperator } from 'overmind'

export function filter(operation) {
  return createOperator(
    'filter',
    operation.name,
    (err, context, value, next, final) => {
      if (err) next(err, value)
      else if (operation(context, value)) next(null, value)
      else final(null, value)
    }
  )
}
```

The **final** argument bypasses any other operators.


# Server Side Rendering

Some projects require you to render your application on the server. There are different reasons to do this, like search engine optimizations, general optimizations and even browser support. What this means for state management is that you want to expose a version of your state on the server and render the components with that state. But that is not all, you also want to **hydrate** the changed state and pass it to the client with the HTML so that it can **rehydrate** and make sure that when the client renders initially, it renders the same UI.

## Preparing the project

When doing server-side rendering the configuration of your application will be shared by the client and the server. That means you need to structure your app to make that possible. There is really not much you need to do.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { state } from './state'

export const config = {
  state
}

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}

{% tab title="index.ts" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

Here we only export the configuration from the main Overmind file. The instantiation rather happens where we prepare the application on the client side. That means we can now safely import the configuration also on the server.

## Preparing effects

The effects will also be shared with the server. Typically this is not an issue, but you should be careful about creating effects that run logic when they are defined. You might also consider lazy-loading effects so that you avoid loading them on the server at all. You can read more about them in [EFFECTS](/master-1/core/running-side-effects).

## Rendering on the server

When you render your application on the server you will have to create an instance of Overmind designed for running on the server. On this instance you can change the state and provide it to your components for rendering. When the components have rendered you can **hydrate** the changes and pass them along to the client so that you can **rehydrate**.

{% hint style="info" %}
Overmind does not hydrate the state, but the mutations you performed. That means it minimizes the payload passed over the wire.
{% endhint %}

The following shows a very simple example using an [EXPRESS](https://expressjs.com/) middleware to return a server side rendered version of your app.

{% tabs %}
{% tab title="server/routePosts.ts" %}

```typescript
import { createOvermindSSR } from 'overmind'
import { config } from '../client/overmind'
import db from './db'

export default async (req, res) => {
  const overmind = createOvermindSSR(config)

  overmind.state.currentPage = 'posts'
  overmind.state.posts = await db.getPosts()

  const html = renderToString(
    // Whatever implementation your view layer provides
  )

  res.send(`
<html>
  <body>
    <div id="app">${html}</div>
    <script>
      window.__OVERMIND_MUTATIONS = ${JSON.stringify(overmind.hydrate())}
    </script>
    <script src="/scripts/app.js"></script>
  </body>
</html>
`)
}
```

{% endtab %}
{% endtabs %}

## Rehydrate on the client

On the client you just want to make sure that your Overmind instance rehydrates the mutations performed on the server so that when the client renders, it does so with the same state. The **onInitialize** hook of Overmind is the perfect spot to do this.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize, rehydrate } from 'overmind'

export const onInitialize: OnInitialize = ({ state }) => {
  const mutations = window.__OVERMIND_MUTATIONS

  rehydrate(state, mutations)
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
If you are using state first routing, make sure you prevent the router from firing off the initial route, as this is not needed.
{% endhint %}

## OnInitialize

The `onInitialized` action does not run on the server. The reason is that it is considered a side effect you might not want to run, so we do not force it. If you do want to run an action as Overmind fires up both on the client and the server you can rather create a custom action for it.

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const initialize = () => {
  // Whatever...
}
```

{% endtab %}

{% tab title="client/index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
overmind.actions.initialize()
```

{% endtab %}

{% tab title="server/index.js" %}

```javascript
import { createOvermindSSR } from 'overmind'
import { config } from '../client/overmind'

export default async (req, res) => {
  const overmind = createOvermindSSR(config)
  await overmind.actions.initialize()

  const html = renderToString(
    // Whatever implementation your view layer provides
  )

  res.send(`
<html>
  <body>
    <div id="app">${html}</div>
    <script>
      window.__OVERMIND_MUTATIONS = ${JSON.stringify(overmind.hydrate())}
    </script>
    <script src="/scripts/app.js"></script>
  </body>
</html>
`)
}
```

{% endtab %}
{% endtabs %}

## Next.js

The idea behind setting up overmind in `next.js` is the same as a standard express server but we have a lot of help from next to get us going.

Let's start by adding a `_document.js` and this is where we will initialize the SSR version of Overmind:

{% tabs %}
{% tab title="src/\_document.js" %}

```javascript
import App from "next/app";
import { createOvermind, createOvermindSSR, rehydrate } from "overmind";
import { Provider } from "overmind-react";
import { config } from "../overmind";

export default class MyApp extends App {
  // CLIENT: On initial route
  // SERVER: On initial route
  constructor(props) {
    super(props);

    const mutations = props.pageProps.mutations || [];

    if (typeof window !== "undefined") {
      // On the client we just instantiate the Overmind instance and run
      // the "changePage" action
      this.overmind = createOvermind(config);
      this.overmind.actions.changePage(mutations);
    } else {
      // On the server we rehydrate the mutations to an SSR instance of Overmind,
      // as we do not want to run any additional logic here
      this.overmind = createOvermindSSR(config);
      rehydrate(this.overmind.state, mutations);
    }
  }
  // CLIENT: After initial route, on page change
  // SERVER: never
  componentDidUpdate() {
    // This runs whenever the client routes to a new page
    this.overmind.actions.changePage(this.props.pageProps.mutations || []);
  }
  render() {
    const { Component, pageProps } = this.props;
    return (
      <Provider value={this.overmind}>
        <Component {...pageProps} />
      </Provider>
    );
  }
}
```

{% endtab %}
{% endtabs %}

And then let's create a standard `Overmind` instance:

```javascript
import { rehydrate } from "overmind";
import { createHook } from "overmind-react";

export const config = {
  state: {},
  actions: {
  add
    changePage({ state }, mutations) {
      rehydrate(state, mutations || []);
    }
  }
};

export const useOvermind = createHook();
```

And you are all set to get going with `overmind` and `next.js`. You can also take a look at [this example in the next.js examples directory](https://github.com/vercel/next.js/tree/canary/examples/with-overmind) if you need some help.

## Gatsby

When it comes to gatsby we need to prepare Overmind for static extraction and the idea is about the same.

We need first to wrap our whole app in the Overmind provider and we can do that in `gatsby-browser.js`:

```javascript
import React from "react"
import { createOvermind } from "overmind"
import { Provider } from "overmind-react"
import { config } from "./src/overmind"

const overmind = createOvermind(config);

export const wrapPageElement = ({ element }) => (
  <Provider value={createOvermind(config)}>
    {element}
  </Provider>
)
```

After this is done we can do the same thing for the server render and add that code in the `gatsby-ssr.js` file:

```javascript
import React from "react"
import { Provider } from "overmind-react"
import { createOvermindSSR } from "overmind"
import { ThemeProvider as ChakraProvider } from "@chakra-ui/core"
import { theme } from "@chakra-ui/core"
import { config } from "./src/overmind"

const overmind = createOvermindSSR(config)

export const wrapPageElement = ({ element }) => (
  <Provider value={createOvermind(config)}>
    {element}
  </Provider>
)
```

As you can see the only difference we have here is that we createOvermindSSR in the `gatsby-ssr.js`


# Typescript

Overmind is written in Typescript and it is written with a focus on you dedicating as little time as possible to help Typescript understand what your app is all about. Typescript will spend a lot more time helping you. If you are not a Typescript developer Overmind is a really great project to start learning it as you will get the most out of the little typing you have to do.

## Configuration

First we need to define the typing of our configuration and there are two approaches to that.

### 1. Declare module

The most straightforward way to type your application is to use the **declare module** approach. This will work for most applications, but might make you feel uncomfortable as a hardcore Typescripter. The reason is that we are overriding an internal type, meaning that you can only have one instance of Overmind running inside your application.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'

const config = {}

declare module 'overmind' {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
  interface Config extends IConfig<{
    state: typeof config.state,
    actions: typeof config.actions,
    effects: typeof config.effects
  }> {}
  // Due to circular typing we have to define an
  // explicit typing of state, actions and effects since
  // TS 3.9
}
```

{% endtab %}
{% endtabs %}

Now you can import any type directly from Overmind and it will understand the configuration of your application. Even the operators are typed.

```typescript
import {
  Context,
  RootState,
  pipe,
  map,
  filter,
  ...
} from 'overmind'
```

### 2. Explicit typing

You can also explicitly type your application. This gives more flexibility.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import {
  IConfig,
  IOnInitialize,
  IContext,
} from 'overmind'

export const config = {}

// Due to circular typing we have to define an
// explicit typing of state, actions and effects since
// TS 3.9
export interface Config extends IConfig<{
  state: typeof config.state,
  actions: typeof config.actions,
  effects: typeof config.effects
}> {}

export interface OnInitialize extends IOnInitialize<Config> {}

export interface Context extends IContext<Config> {}

// Used with derived
export type RootState = Context['state']
```

{% endtab %}
{% endtabs %}

You only have to set up these types once, where you bring your configuration together. That means if you use multiple namespaced configuration you still only create one set of types, as shown above.

Now you only have to make sure that you import your types from this file, instead of directly from the Overmind package.

{% hint style="info" %}
The Overmind documentation is written for implicit typing. That means whenever you see a type import directly from the Overmind package, you should rather import from your own defined types.
{% endhint %}

## State

The state you define in Overmind is just an object where you type that object.

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
type State = {
  foo: string
  bar: boolean
  baz: string[]
  user: User
}

export const state: State = {
  foo: 'bar',
  bar: true,
  baz: [],
  user: new User()
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
It is important that you use a **type** and not an **interface.** This has to do with the way Overmind resolves the state typing. *\*\**
{% endhint %}

When writing Typescript you should **not** use optional values for your state (**?**), or use **undefined** in a union type. In a serializable state store world **null** is the value indicating *“there is no value”.*

```typescript
type State = {
  // Do not do this
  foo?: string

  // Do not do this
  foo: string | undefined

  // Do this
  foo: string | null

  // Or this, if there always will be a value there
  foo: string
}

export const state: State = {
  foo: null
}
```

### Derived

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { derived } from 'overmind'

type State = {
  foo: string
  shoutedFoo: string
}

export const state: State = {
  foo: 'bar',
  shoutedFoo: derived((state: State) => state.foo + '!!!')
}
```

{% endtab %}
{% endtabs %}

Note that the type argument you pass is the object the derived is attached to, so with nested derived:

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { derived } from 'overmind'

type State = {
  foo: string
  nested: {
    shoutedFoo: string
  }
}

export const state: State = {
  foo: 'bar',
  nested: {
    shoutedFoo: derived((state: State['nested']) => state.foo + '!!!')
  }
}
```

{% endtab %}
{% endtabs %}

Note that with **Explicit Typing** you need to also pass the a third argument to the **derived** function, the **Config** type created in your main **index.ts** file.

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { RootState } from 'overmind'

type State = {
  foo: string
  shoutedFoo: string
}

export const state: State = {
  foo: 'bar',
  shoutedFoo: derived(
    (state: State, rootState: RootState) => state.foo + '!!!'
  )
}
```

{% endtab %}
{% endtabs %}

### Statemachine

Read the guide on [**Using state machines**](/master-1/guides-1/using-state-machines) to understand how to type them.

## Actions

You type your actions with the **Context** and an optional value. Any return type will be inferred.

```typescript
import { Context } from 'overmind'

export const noArgAction = (context: Context) => {
  // actions.noArgAction()
}

export const argAction = (context: Context, value: string) => {
  // actions.argAction("foo"), requires "string"
}

export const noArgWithReturnTypeAction = (context: Context) => {
  // actions.noArgWithReturnTypeAction(), with return type "string"
  return 'foo'
}

export const argWithReturnTypeAction = (context: Context, value: string) => {
  // actions.argWithReturnTypeAction("foo"), requires "string" and returns "string"
  return value + '!!!'
}
```

Any of these actions could be defined as an **async** function or simply return a promise to be typed that way.

## Effects

There are no Overmind specific types related to effects, you just type them in general.

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
export const api = {
  getUser: async (): Promise<User> => {
    const response = await fetch('/user')

    return response.json()
  }
}
```

{% endtab %}
{% endtabs %}

## Operators

Operators is like the action: it can take an optional value, but it always produces an output. By default the output of an operator is the same as the input.

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Context, mutate, filter, map } from 'overmind'

// Use the Context type for the first argument
export const changeSomeState = mutate(({ state }: Context) =>  {
  state.foo = 'bar'
})

// Type the value as the second argument
export const filterAwesomeUser = filter((_: Context, user: User) => {
  return user.isAwesome
})

// The output is inferred
export const toNumber = map((_: Context, value: number) => { 
  return Number(value)
})
```

{% endtab %}
{% endtabs %}

When you create a **pipe** that has an input when it is called you only need to type the first operator value.

```typescript
import { Context, pipe, map, mutate } from 'overmind'

export const doThis = pipe(
  map((context: Context, value: string) => {
    // actions.doThis("foo"), requires "string"
    return 123
  }),
  mutate((context: Context, value) => {
    // value is now "number"
  })
```


# React

## Install

```
npm install overmind overmind-react
```

There are two different ways to connect Overmind to React. You can either use a traditional **Higher Order Component** or you can use the new **hooks** api to expose state and actions.

When you connect Overmind to a component you ensure that whenever any tracked state changes, only components interested in that state will re-render, and will do so “at their location in the component tree”. That means we remove a lot of unnecessary work from React. There is no reason for the whole React component tree to re-render when only one component is interested in a change.

## Hook

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

```typescript
// overmind/index.js
import {
  createStateHook,
  createActionsHook,
  createEffectsHook,
  createReactionHook
} from 'overmind-react'
import { state } from './state'
import * as actions from './actions'

export const config = {
  state,
  actions
}

export const useState = createStateHook()
export const useActions = createActionsHook()
export const useEffects = createEffectsHook()
export const useReaction = createReactionHook()

// index.js
import * as React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import App from './components/App'

const overmind = createOvermind(config)

render((
  <Provider value={overmind}>
    <App />
  </Provider>
), document.querySelector('#app'))

// components/App.jsx
import * as React from 'react'
import { useState, useActions, useEffects, useReaction } from '../overmind'

const App = () => {
  // General
  const state = useState()
  const actions = useActions()
  const effects = useEffects()
  const reaction = useReaction()
  // Or be specific
  const { isLoggedIn } = useState().auth
  const { login, logout } = useActions().auth

  return <div />
}

export default App
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// overmind/index.ts
import { IConfig } from 'overmind'
import { createHook } from 'overmind-react'
import { state } from './state'
import * as actions from './actions'

export const config = {
  state,
  actions
}

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}

export const useOvermind = createHook<typeof config>()
export const useState = createStateHook<typeof config>()
export const useActions = createActionsHook<typeof config>()
export const useEffects = createEffectsHook<typeof config>()
export const useReaction = createReactionHook<typeof config>()

// index.tsx
import * as React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import App from './components/App'

const overmind = createOvermind(config)

render((
  <Provider value={overmind}>
    <App />
  </Provider>
), document.querySelector('#app'))

// components/App.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'

const App: React.FunctionComponent = () => {
  // General
  const { state, actions, effects, reaction } = useOvermind()
  // Or be specific
  const { isLoggedIn } = useState().auth
  const { login, logout } = useActions().auth

  return <div />
}

export default App
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The benefit of using specific hooks is that if you only need actions in a component, you do not add tracking behaviour to the component by using **useActions**. Also it reduces the amount of destructuring needed, as you can point to a namespace on the hook.
{% endhint %}

### Rendering

When you use the Overmind hook it will ensure that the component will render when any tracked state changes. It will not do anything related to the props passed to the component. That means whenever the parent renders, this component renders as well. You will need to wrap your component with [**REACT.MEMO**](https://reactjs.org/docs/react-api.html#reactmemo) to optimize rendering caused by a parent.

### Passing state as props

If you pass a state object or array as a property to a child component you will also in the child component need to use the **useState** hook to ensure that it is tracked within that component, even though you do not access any state or actions. The devtools will help you identify where any components are left “unconnected”.

{% hint style="info" %}
Note that when you pass an **array** you will not be observing changes to the array itself, for example adding/removing items. You will only observe any items you access in the array. The same goes for **object**. You are not observing adding/removing keys from the object. Consider passing the parent of the values instead.
{% endhint %}

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

```typescript
// components/Todos.jsx
import * as React from 'react'
import { useState } from '../overmind'
import Todo from './Todo'

const Todos = () => {
  const state = useState()

  return (
    <ul>
      {state.todos.map(todo => <Todo key={todo.id} todo={todo} />)}
    </ul<
  )
}

export default Todos

// components/Todo.jsx
import * as React from 'react'
import { useState } from '../overmind'

const Todo = ({ todo }) => {
  useState()

  return <li>{todo.title}</li>
}

export default Todo
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// components/Todos.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'
import Todo from './Todo'

const Todos: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.todos.map(todo => <Todo key={todo.id} todo={todo} />)}
    </ul<
  )
}

export default Todos

// components/Todo.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'

type Props = {
  todo: Todo
}

const Todo: React.FunctionComponent<Props> = ({ todo }) => {
  useOvermind()

  return <li>{todo.title}</li>
}

export default Todo
```

{% endtab %}
{% endtabs %}

### Reactions

The hook effect of React gives a natural point of running effects related to state changes. An example of this is from the Overmind website, where we scroll to the top of the page whenever the current page state changes.

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

```typescript
// components/App.jsx
import * as React from 'react'
import { useEffect } from 'react'
import { useState } from '../overmind'

const App = () => {
  const state = useState()

  useEffect(() => {
    document.querySelector('#app').scrollTop = 0
  }, [state.currentPage])

  return <div />
}

export default App
```

{% endtab %}

{% tab title="Typescript" %}

```javascript
// components/App.tsx
import * as React from 'react'
import { useEffect } from 'react'
import { useOvermind } from '../overmind'

const App: React.FunctionComponent = () => {
  const { state } = useOvermind()

  useEffect(() => {
    document.querySelector('#app').scrollTop = 0
  }, [state.currentPage])

  return <div />
}

export default App
```

{% endtab %}
{% endtabs %}

Here you can also use the traditional approach of subscribing to updates.

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

```typescript
// components/App.jsx
import * as React from 'react'
import { useEffect } from 'react'
import { useReaction } from '../overmind'

const Todos = () => {
  const reaction = useReaction()

  useEffect(() => {
    return reaction(
      ({ currentPage }) => currentPage,
      () => document.querySelector('#app').scrollTop = 0
    })
  }, [])

  return <div />
}

export default Todos
```

{% endtab %}

{% tab title="Typescript" %}

```javascript
// components/App.tsx
import * as React from 'react'
import { useEffect } from 'react'
import { useOvermind } from '../overmind'

const Todos: React.FunctionComponent = () => {
  const { reaction } = useOvermind()

  useEffect(() => {
    return reaction(
      ({ currentPage }) => currentPage,
      () => document.querySelector('#app').scrollTop = 0
    })
  }, [])

  return <div />
}

export default Todos
```

{% endtab %}
{% endtabs %}

## Higher Order Component

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

```typescript
// overmind/index.js
import { createConnect } from 'overmind-react'
import { state } from './state'
import * as actions from './actions'

export const config = {
  state,
  actions
}

export const connect = createConnect()

// index.jsx
import * as React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import App from './components/App'

const overmind = createOvermind(config)

render((
  <Provider value={overmind}>
    <App />
  </Provider>
), document.querySelector('#app'))

// components/App.jsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

const App = ({ overmind }) => {
  const { state, actions, effects, addMutationListener } = overmind

  return <div />
}

export default connect(App)
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// overmind/index.ts
import { IConfig } from 'overmind'
import { createConnect, IConnect } from 'overmind-react'
import { state } from './state'
import * as actions from './actions'

export const config = {
  state,
  actions
}

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}

export interface Connect extends IConnect<typeof config> {}

export const connect = createConnect<typeof config>()

// index.tsx
import * as React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import App from './components/App'

const overmind = createOvermind(config)

render((
  <Provider value={overmind}>
    <App />
  </Provider>
), document.querySelector('#app'))

// components/App.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

type Props = {} & Connect

const App: React.FunctionComponent<Props> = ({ overmind }) => {
  const { state, actions, effects, addMutationListener } = overmind

  return <div />
}

export default connect(App)
```

{% endtab %}
{% endtabs %}

### Rendering

When you connect a component with the **connect HOC** it will be responsible for tracking and trigger a render when the tracked state is updated. The **overmind** prop passed to the component you defined holds the state and actions. If you want to detect inside your component that it was indeed an Overmind state change causing the render you can compare the **overmind** prop itself.

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

```typescript
// components/App.jsx
import * as React from 'react'
import { connect } from '../overmind'

class App extends React.Component {
  shouldComponentUpdate(nextProps) {
    return this.props.overmind !== nextProps.overmind
  }
  render() {
    return <div />
  }
}

export default connect(App)
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// components/App.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

type Props = {} & Connect

class App extends React.Component<Props> {
  shouldComponentUpdate(nextProps: Props) {
    return this.props.overmind !== nextProps.overmind
  }
  render() {
    return <div />
  }
}

export default connect(App)
```

{% endtab %}
{% endtabs %}

You will not be able to compare a previous state value in Overmind with the new. That is simply because Overmind is not immutable and it should not be. You will not use **shouldComponentUpdate** to compare state in Overmind, though you can of course still use it to compare props from a parent. This is a bit of a mindshift if you come from Redux, but it actually removes the mental burden of doing this stuff.

If you previously used **componentDidUpdate** to trigger an effect, that is no longer necessary either. You rather listen to state changes in Overmind using **addMutationListener** specified below in *effects*.

### Passing state as props

If you pass a state object or array as a property to a child component you will also in the child component need to **connect**. This ensures that the property you passed is tracked within that component, even though you do not access any state or actions from Overmind. The devtools will help you identify where any components are left “unconnected”.

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

```typescript
// components/Todos.jsx
import * as React from 'react'
import { connect } from '../overmind'
import Todo from './Todo'

const Todos = ({ overmind }) => {
  const { state } = overmind

  return (
    <ul>
      {state.todos.map(todo => <Todo key={todo.id} todo={todo} />)}
    </ul<
  )
}

export default connect(Todos)

// components/Todo.tsx
import * as React from 'react'
import { connect } from '../overmind'

const Todo = ({ todo }) => {
  return <li>{todo.title}</li>
}

export default connect(Todo)
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// components/Todos.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'
import Todo from './Todo'

type Props = {} & Connect

const Todos: React.FunctionComponent<Props> = ({ overmind }) => {
  const { state } = overmind

  return (
    <ul>
      {state.todos.map(todo => <Todo key={todo.id} todo={todo} />)}
    </ul<
  )
}

export default connect(Todos)

// components/Todo.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

type Props = {
  todo: Todo
} & Connect

const Todo: React.FunctionComponent<Props> = ({ todo }) => {
  return <li>{todo.title}</li>
}

export default connect(Todo)
```

{% endtab %}
{% endtabs %}

### Reactions

To run reactions in components based on changes to state you use the **reaction** function in the lifecycle hooks of React.

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

```typescript
// components/App.jsx
import * as React from 'react'
import { connect } from '../overmind'

class App extends React.Component {
  private disposeReaction
  componentDidMount() {
    this.disposeReaction = this.props.overmind.reaction(
      (state) => state.currentPage,
      () => document.querySelector('#app').scrollTop = 0
    )
  }
  componentWillUnmount() {
    this.disposeReaction()
  }
  render() {
    const { state, actions } = this.props.overmind

    return <div />
  }
}

export default connect(App)
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// components/App.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

type Props = {} & Connect

class App extends React.Component<Props> {
  disposeReaction: () => void
  componentDidMount() {
    this.disposeReaction = this.props.overmind.reaction(
      (state) => state.currentPage,
      () => document.querySelector('#app').scrollTop = 0
    )
  }
  componentWillUnmount() {
    this.disposeReaction()
  }
  render() {
    const { state, actions } = this.props.overmind

    return <div />
  }
}

export default connect(App)
```

{% endtab %}
{% endtabs %}

## React Native

Overmind supports React Native with **hook** and **Higher Order Component**. What to take notice of though is that native environments sometimes hides the **render** function of React. That can be a bit confusing in terms of setting up the **Provider**. If your environment only exports an initial component, that component needs to be responsible for settings up the providers and rendering your main component:

```typescript
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import MyApp from './MyApp'

const overmind = createOvermind(config)

export function App() {
  return (
    <Provider value={overmind}>
      <MyApp />
    </Provider>
  )
}
```


# Angular

## Install

```
npm install overmind overmind-angular
```

## Configure

Let us have a look at how you configure your app:

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { Injectable } from '@angular/core'
import { OvermindService } from 'overmind-angular'
import { state } from './state'
import * as actions from './actions'

export const config = { state, actions }

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}

@Injectable({
  providedIn: 'root'
})
export class Store extends OvermindService<typeof config> {}
```

{% endtab %}

{% tab title="app.module.ts" %}

```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { createOvermind } from 'overmind';
import { OvermindModule, OvermindService, OVERMIND_INSTANCE } from 'overmind-angular'

import { config, Store } from './overmind'
import { AppComponent } from './app.component';

@NgModule({
  imports: [ BrowserModule, OvermindModule ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ],
  providers: [
    { provide: OVERMIND_INSTANCE, useFactory: () => createOvermind(config) },
    { provide: Store, useExisting: OvermindService }
]
})
export class AppModule { }
```

{% endtab %}

{% tab title="components/app.component.ts" %}

```typescript
import { Component, ChangeDetectionStrategy } from '@angular/core'
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
<div *track>
  <h1 (click)="actions.changeTitle()">{{ state.title }}</h1>
</div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  state = this.store.select()
  actions = this.store.actions
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="main.ts" %}

```typescript
import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

import { AppModule } from "./app/app.module";
import { environment } from "./environments/environment";

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule, {
    // We do not need zones, we rather use the tracking
    // directive, which gives us a pretty signifcant performance
    // boost. Note that 3rd party libraries might need ngZone,
    // in which case you can not set it to "noop"
    ngZone: "noop"
  })
  .catch(err => console.log(err));
```

{% endtab %}
{% endtabs %}

The **service** is responsible for exposing the configuration of your application. The **\*track** directive is what does the actual tracking. Just put it at the top of your template and whatever state you access will be optimally tracked. You can also select a namespace from your state to expose to the component:

{% tabs %}
{% tab title="components/app.component.ts" %}

```typescript
import { Component, ChangeDetectionStrategy } from '@angular/core'
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
<div *track>
  <h1 (click)="actions.changeAdminTitle()">{{ state.adminTitle }}</h1>
</div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  state = this.store.select(state => state.admin)
  actions = this.store.actions.admin
  constructor(private store: Store) {}
},
```

{% endtab %}
{% endtabs %}

You can now access the **admin** state and actions directly with **state** and **actions**.

### Polyfill environment

Angular does not inject the environment, so in your **polyfill.ts** file you have to add the following:

```typescript
import { environment } from './environments/environment';

(window as any).process = {
  env: {
    NODE_ENV: environment.production ? 'production' : 'development'
  },
};
```

## NgZone

The Overmind **\*track** directive knows when your components should update, and so is much more efficient at change detection than Angular's default NgZone. In order to take advantage of the efficiency provided by the \***track** directive, you *must* set **ngZone** to "noop". Note that other 3rd party libraries may not support this. If for any reason you can't set **ngZone** to "noop", then the \***track** directive is redundant, and you can safely exclude it from your templates.

## Rendering

When you connect Overmind to your component and expose state you do not have to think about how much state you expose. The exact state that is being accessed in the template is the state that will be tracked. That means you can expose all the state of the application to all your components without worrying about performance.

## Passing state as input

When you pass state objects or arrays as input to a child component that state will by default be tracked on the component passing it along, which you can also see in the devtools. By just adding the **\*tracker** directive to the child template, the tracking will be handed over:

{% tabs %}
{% tab title="components/todo.component.ts" %}

```typescript
import { Component, Input, ChangeDetectionStrategy } from '@angular/core'
import { Todo } from '../overmind/state'

@Component({
  selector: 'todos-todo',
  template: `
<li *track>{{ todo.title }}</li>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TodoComponent {
  @Input() todo: Todo
}
```

{% endtab %}

{% tab title="components/todos.component.ts" %}

```typescript
import { Component, ChangeDetectionStrategy } from '@angular/core'
import { Store } from '../overmind'

@Component({
  selector: 'todos-list',
  template: `
<ul *track>
  <todos-todo *ngFor="let todo of state.todos;" [todo]="todo"></todos-todo>
</ul>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ListComponent {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endtab %}
{% endtabs %}

What is important to understand here is that Overmind is **not** immutable. That means if you would change any property on any todo, only the component actually looking at the todo will render. The list is untouched.

## Reactions

To run effects in components based on changes to state you use the **reaction** function in the lifecycle hooks of Angular.

{% tabs %}
{% tab title="components/app.component.ts" %}

```typescript
import { Component } from '@angular/core'
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  disposeReaction: () => void
  constructor (private store: Store) {}
  ngOnInit() {
    this.disposeReaction = this.store.reaction(
      ({ currentPage }) => currentPage,
      () => document.querySelector('#app').scrollTop = 0
    )
  }
  ngOnDestroy() {
    this.disposeReaction()
  }
}
```

{% endtab %}
{% endtabs %}


# Vue

## Install

```
npm install overmind overmind-vue
```

There are three approaches to connecting Overmind to Vue.

## Hooks (experimental)

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { createHooks } from 'overmind-vue'

export const config = {
  state: {
    foo: 'bar'
  },
  actions: {
    onClick() {}
  }
}

export const hooks = createHooks()
```

{% endtab %}

{% tab title="index.js" %}

```javascript
import { createApp } from 'vue'
import { createOvermind } from 'overmind'
import { withOvermind } from 'overmind-vue'
import { config } from './overmind'
import App from './App.vue'

const overmind = createOvermind(config)

createApp(withOvermind(overmind, App)).mount('#app')

...
```

{% endtab %}

{% tab title="components/SomeComponent.vue" %}

```javascript
<template>
  <div @click="actions.onClick">
    {{ state.foo }}
  </div>
</template>
<script>
  import { hooks } from '../overmind'

  export default {
    setup() {
      const state = hooks.state()
      const actions = hooks.actions()

      return { state, actions }
    }
  }
</script>
```

{% endtab %}
{% endtabs %}

The hooks also allows you to point to specific namespaces:

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```javascript
<template>
  <div @click="actions.onClick">
    {{ state.foo }}
  </div>
</template>
<script>
  import { hooks } from '../overmind'

  export default {
    setup() {
      const state = hooks.state(state => state.admin)
      const actions = hooks.actions(actions => actions.admin)

      return { state, actions }
    }
  }
</script>
```

{% endtab %}
{% endtabs %}

You also have **effects** and **reaction** available on your hooks:

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```javascript
  <div @click="actions.onClick">
    {{ state.foo }}
  </div>
</template>
<script>
  import { hooks } from '../overmind'

  export default {
    setup() {
      const effects = hooks.effects()
      const reaction = hooks.reaction()

      return { state, actions }
    }
  }
</script>
```

{% endtab %}
{% endtabs %}

If you prefer using JSX, that is also possible:

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```javascript
<script>
  import { hooks } from '../overmind'

  export default {
    setup() {
      const state = hooks.state()
      const actions = hooks.actions()

      return () => (
        <div onClick={actions.onClick}>{state.value.foo}</div>
      )
    }
  }
</script>
```

{% endtab %}
{% endtabs %}

## Plugin

Vue has a plugin system that allows us to expose Overmind to all components. This allows minimum configuration and you just use state etc. from any component.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
export const overmind = {
  state: {
    foo: 'bar'
  },
  actions: {
    onClick() {}
  }
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import Vue from 'vue/dist/vue'
import { createOvermind } from 'overmind'
import { createPlugin } from 'overmind-vue'
import { config } from './overmind'

const overmind = createOvermind(config)
const OvermindPlugin = createPlugin(overmind)

Vue.use(OvermindPlugin)

...
```

{% endtab %}

{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="actions.onClick">
    {{ state.foo }}
  </div>
</template>
```

{% endtab %}
{% endtabs %}

If you rather want to expose state, actions and effects differently you can configure that.

{% tabs %}
{% tab title="index.js" %}

```typescript
import Vue from 'vue/dist/vue'
import { createOvermind } from 'overmind'
import { createPlugin } from 'overmind-vue'
import { config } from './overmind'

const overmind = createOvermind(config)
const OvermindPlugin = createPlugin(overmind)

Vue.use(OvermindPlugin, ({ state, actions, effects }) => ({
  admin: state.admin,
  posts: state.posts,
  actions,
  effects
}))

...
```

{% endtab %}

{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="actions.onClick">
    {{ admin.foo }} {{ posts.foo }}
  </div>
</template>
```

{% endtab %}
{% endtabs %}

### Rendering

Any state accessed in the component will cause the component to render when a mutation occurs on that state. Overmind actually uses the same approach to change detection as Vue itself. When using the plugin any component can access any state, though the only overhead that is added to the application is an instance of a “tracking tree” per component. This might sound scary, but it is a tiny little object that adds a callback function to Overmind as long as the component lives. These tracking trees are even reused as components unmount.

### Pass state as props

If you pass anything from the state to a child component it will just work out of the box. The child component will “rescope” the property to its own tracking tree. This ensures that the property you passed is tracked within that component.

{% tabs %}
{% tab title="components/Todo.vue" %}

```typescript
<template>
  <li>{{ todo.title }}</li>
</template>
<script>
export default {
  name: 'Todo',
  props: ["todo"]
}
</script>
```

{% endtab %}

{% tab title="components/Todos.vue" %}

```typescript
<template>
  <ul>
    <todo-component
      v-for="post in state.postsList"
      :todo="todo"
      :key="todo.id"
    ></todo-component>
  </ul>
</template>
<script>
import TodoComponent from './Todo'

export default {
  name: 'Todo',
  components: {
    TodoComponent
  }
}
</script>
```

{% endtab %}
{% endtabs %}

### Reactions

To run effects in components based on changes to state you use the **reaction** function in the lifecycle hooks of Vue.

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="overmind.actions.onClick">
    {{ overmind.state.foo }}
  </div>
</template>
<script>
import { connect } from '../overmind'

export default connect({
  mounted() {
    this.disposeReaction = this.overmind.reaction(
      ({ currentPage }) => currentPage,
      () => document.querySelector('#app').scrollTop = 0
    )
  },
  destroyed() {
    this.disposeReaction()
  }
})
</script>
```

{% endtab %}
{% endtabs %}

## Connect

If you want more manual control of what components connect to Overmind you can use the connector.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { createConnect } from 'overmind-vue'

const overmind = createOvermind({
  state: {},
  actions: {}
})

export const connect = createConnect(overmind)
```

{% endtab %}

{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="overmind.actions.onClick">
    {{ overmind.state.foo }}
  </div>
</template>
<script>
import { connect } from '../overmind'

const Component = {}

export default connect(Component)
</script>
```

{% endtab %}
{% endtabs %}

You can also expose parts of the configuration on custom properties of the component:

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="actions.someAdminAction">
    {{ state.someAdminState }}
  </div>
</template>
<script>
import { connect } from '../overmind'

const Component = {}

export default connect(({ state, actions, effects }) => ({
  state: state.admin,
  actions: actions.admin
}), Component)
</script>
```

{% endtab %}
{% endtabs %}

You can now access the **admin** state and actions directly with **state** and **actions**.

## Computed

Vue has its own observable concept that differs from Overmind. That means you can not use Overmind state inside a computed and expect the computed cache to be busted when the Overmind state changes. But computeds are really for caching expensive computation, which you will rather do inside Overmind using **derived** anyways.

## Using props

You can combine Overmind state with props to dynamically extract state.

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div>
    {{ title }}
  </div>
</template>
<script>
export default {
  name: 'SomeComponent',
  props: ["id"],
  data: (self) => ({
    get title() {
      return self.state.titles[self.id]
    }
  })
}
</script>
```

{% endtab %}
{% endtabs %}


# Svelte

There are two differente ways to connect Overmind to Svelte. You can use the **reactive declarations** or you can use the **reaction**.

When you connect Overmind to a component you ensure that whenever any tracked state changes, only components interested in that state will re-render.

## Reactive declarations

```javascript
import { createOvermind } from 'overmind'
import { createMixin } from 'overmind-svelte'

const overmind = {
  state: {
    count: 0
  },
  actions: {
    increase({ state }) {
      state.count++;
    },
    decrease({ state }) {
      state.count--;
    }
  }
}

const store = createMixin(createOvermind(overmind))

export const state = store.state
export const actions = store.actions
```

```javascript
<script>
  import { state, actions } from './overmind.js'

  $: count = $state.count
</script>

<p>Count: {count}</p>
<button id="increase" on:click={() => store.actions.increase()}>Increase</button>
<button id="decrease" on:click={() => store.actions.decrease()}>Increase</button>
```

## Reactions

```javascript
import { createOvermind } from 'overmind'
import { createMixin } from 'overmind-svelte'

const overmind = {
  state: {
    count: 0
  },
  actions: {
    increase({ state }) {
      state.count++;
    },
    decrease({ state }) {
      state.count--;
    }
  }
}

const store = createMixin(createOvermind(overmind))

export const state = store.state
export const actions = store.actions
export const reactions = store.reactions
```

```javascript
<script>
  import { state, actions, reactions } from './overmind.js'

  $: count = $state.count
  let doubled = undefined
  store.reaction(
    (state) => state.count,
    (value) => {
        doubled = value * 2
    },
    {
        immediate: true
    }
  )
</script>

<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
<button id="increase" on:click={() => store.actions.increase()}>Increase</button>
<button id="decrease" on:click={() => store.actions.decrease()}>Increase</button>
```


# GraphQL

Using Graphql with Overmind gives you the following benefits:

* **Query:** The query for data is run with the rest of your application logic, unrelated to mounting components
* **Cache:** You integrate the data from Graphql with your existing state, allowing you to control when new data is needed
* **Optimistic updates:** With the data integrated with your Overmind state you can also optimistically update that state before running a mutation query

## Get up and running

Install the separate package:

```
npm install overmind-graphql
```

### Initial state

The Graphql package is an *effect*. Though since we are operating on state, let us prepare some:

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="overmind/state.js" %}

```typescript
export const state = {
  posts: []
}
```

{% endtab %}
{% endtabs %}

### The effect

Now let us introduce the effect:

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'
import { onInitialize } from './onInitialize'
import { gql } from './effects/gql'

export const config = {
  onInitialize,
  state,
  effects: {
    gql
  }
}
```

{% endtab %}

{% tab title="overmind/onInitialize.js" %}

```javascript
export const onInitialize = ({ effects }) => {
  effects.gql.initialize({
    // query and mutation options
    endpoint: 'http://some-endpoint.dev',
  }, {
    // subscription options
    endpoint: 'ws://some-endpoint.dev',  
  })
}
```

{% endtab %}

{% tab title="overmind/effects/gql/index.js" %}

```javascript
import { graphql } from 'overmind-graphql'
import * as queries from './queries'
import * as mutations from './mutations'
import * as subscriptions from './subscriptions'

export const gql = graphql({
  queries,
  mutations,
  subscriptions
})
```

{% endtab %}

{% tab title="overmind/effects/gql/queries.js" %}

```typescript
import { gql } from 'overmind-graphql'

export const posts = gql`
  query Posts {
    posts {
      id
      title
    }
  }
`;
```

{% endtab %}

{% tab title="overmind/effects/gql/mutations.js" %}

```typescript
import { gql } from 'overmind-graphql'

export const createPost = gql`
  mutation CreatePost($title: String!) {
    createPost(title: $title) {
      id
    }
  }
`
```

{% endtab %}

{% tab title="overmind/effects/gql/subscriptions.js" %}

```javascript
import { gql } from 'overmind-graphql'

export const onPostAdded = gql`
  subscription PostAdded() {
    postAdded() {
      id
      title
    }
  }
`
```

{% endtab %}
{% endtabs %}

You define **queries,** **mutations** and **subscriptions** with the effect. That means you can have multiple effects holding different queries and even endpoints. The endpoints are defined when you initialize the effect. This allows you to dynamically create the endpoints based on state, and also pass state related to requests to the endpoints. The queries, mutations and subscriptions are converted into Overmind effects that you can call from your actions.

## Query

To call a query you will typically use an action. Let us create an action that uses our **posts** query.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPosts = async ({ state, effects }) => {
  const { posts } = await effects.gql.queries.posts()

  state.posts = posts
}
```

{% endtab %}
{% endtabs %}

## Mutate

Mutation queries are basically the same as normal queries. You would typically also call these from an action.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPosts = async ({ state, effects }) => {
  const { posts } = await effects.gql.queries.posts()

  state.posts = posts
}

export const addPost = async ({ effects }, title) => {
  await effects.gql.mutations.createPost({ title })
}
```

{% endtab %}
{% endtabs %}

## Subscription

Subscriptions are also available via actions. You typically give them an action which triggers whenever the subscription triggers.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPosts = async ({ state, effects, actions }) => {
  const { posts } = await effects.gql.queries.posts()

  state.posts = posts

  effects.gql.subscriptions.onPostAdded(actions.onPostAdded)
}

export const addPost = async ({ effects }, title) => {
  await effects.gql.mutations.createPost({ title })
}

export const onPostAdded = ({ state }, post) => {
  state.posts.push(post)
}
```

{% endtab %}
{% endtabs %}

## Cache

Now that we have the data from our query in the state, we can decide ourselves when we want this data to update. It could be related to moving back to a certain page, maybe you want to update the data in the background or maybe it is enough to just grab it once. You do not really think about it any differently here than with any other data fetching solution.

## Optimistic updates

Again, since our data is just part of our state we are in complete control of optimistically adding new data. Let us create an optimistic post.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPosts = async ({ state, effects }) => {
  const { posts } = await effects.queries.posts()

  state.posts = posts
}

export const addPost = async ({ state, effects }, title) => {
  const optimisticId = String(Date.now())

  state.posts.push({
    id: optimisticId,
    title
  })

  const { id } = await effects.mutations.createPost({ title })
  const optimisticPost = state.posts.find(post => post.id === optimisticId)

  optimisticPost.id = id
}
```

{% endtab %}
{% endtabs %}

## Options

There are two points of options in the Graphql factory. The **headers** and the **options**.

The headers option is a function which receives the state of the application. That means you can produce request headers dynamically. This can be useful related to authentciation.

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = ({ state, effects }) => {
  effects.gql.initialize({
    endpoint: 'http://some-endpoint.dev',
    // This runs on every request
    headers: () => ({
      authorization: `Bearer ${state.auth.token}`
    }),
    // The options are the options passed to GRAPHQL-REQUEST
    options: {
      credentials: 'include',
      mode: 'cors',
    },
  }, {
    endpoint: 'ws://some-endpoint.dev',
    // This runs on every connect
    params: () => ({
      token: state.auth.token
    })
  })
}
```

{% endtab %}
{% endtabs %}

## Custom subscription socket

If you want to define your own socket for connecting to subscriptions, a function can be used instead:

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```javascript
export const onInitialize = ({ effects }) => {
  effects.gql.initialize(
    {
      endpoint: 'http://some-endpoint.dev',
    }, 
    () => new Websocket('ws://some-other-endpoint.dev')
  )
}
```

{% endtab %}
{% endtabs %}

## Disposing subscriptions

You can dispose any subscriptions in any action. There are two ways to dispose:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const disposeSubscriptions = async ({ state, effects }) => {
  // Disposes all subscriptions on "onPostAdded"
  effects.gql.subscriptions.onPostAdded.dispose()
  // If the subscription takes a payload, you can dispose specific
  // subscriptions
  effects.gql.subscriptions.onPostChange.disposeWhere(
    data => data.id === state.currentPostId
  )
}
```

{% endtab %}
{% endtabs %}

## Typescript

There is only a single type exposed by the library, **Query**. It is used for queries, mutations and subscriptions.

{% tabs %}
{% tab title="overmind/queries.ts" %}

```typescript
import { Query, gql } from 'overmind-graphql'
// You will understand this very soon
import { Posts } from './graphql-types'

export const posts: Query<Posts> = gql`
  query Posts {
    posts {
      id
      title
    }
  }
`;
```

{% endtab %}
{% endtabs %}

The first **Query** argument is the result of the query. There is also a second query argument which is the payload to the query, as seen here.

{% tabs %}
{% tab title="overmind/mutations.ts" %}

```typescript
import { Query, gql } from 'overmind-graphql'
// You will understand this very soon
import { CreatePost, CreatePostVariables } from './graphql-types'

export const createPost: Query<CreatePost, CreatePostVariables> = gql`
  mutation CreatePost($title: String!) {
    createPost(title: $title) {
      id
    }
  }
`
```

{% endtab %}
{% endtabs %}

### Generate typings

It is possible to generate all the typings for the queries and mutations. This is done by using the [APOLLO](https://www.apollographql.com/) project CLI. Install it with:

```
npm install apollo --save-dev
```

Now you can create a script in your **package.json** file that looks something like:

```typescript
{
  "scripts": {
    "schema": "apollo schema:download --header='X-Hasura-Admin-Secret: password' --endpoint=http://some-endpoint.dev graphql-schema.json && apollo codegen:generate --localSchemaFile=graphql-schema.json --target=typescript --includes=src/overmind/**/*.ts --tagName=gql --no-addTypename --globalTypesFile=src/overmind/graphql-global-types.ts graphql-types"
  }
}
```

To update your types, simply run:

```
npm run schema
```

Apollo will look for queries defined with the **gql** template tag and automatically produce the typings. That means whenever you add, remove or update a query in your code you should run this script to update the typings. It also produces what is called **graphql-global-types**. These are types related to fields on your queries, which can be used in your state definition and/or actions.

{% hint style="info" %}
Note that initially you have to define your queries without types and after running the script you can start typing them to get typing in your app and ensure that your app does not break when you change the queries either in the client or on the server
{% endhint %}

## Optimize query

It is possible to transpile the queries from strings into code. This reduces the size of your bundle, though only noticeably if you have a lot of queries. This can be done with the [BABEL-PLUGIN-GRAPHQL-TAG](https://github.com/gajus/babel-plugin-graphql-tag).


# Statechart

{% hint style="info" %}
Before you dive into statecharts it can be a good idea to explore [**statemachines**](/master-1/core/defining-state#statemachines). These are lower level and more flexible and can in most situations be exactly what you need.
{% endhint %}

Just like [OPERATORS](/master-1/core/going-functional) is a declarative abstraction over plain actions, **statecharts** is a declarative abstraction over an Overmind configuration of **state** and **actions**. That means you will define your charts by:

```typescript
const configWithStatechart = statechart(config, chart)
```

There are several benefits to using statecharts:

1. You will have a declarative description of what actions should be available in certain states of the application
2. Less bugs because an invalid action will not be executed if called
3. You will be able to implement and test an interaction flow without building the user interface for it
4. Your state definition is cleaned up as your **isLoading** types of state is no longer needed
5. You have a tool to do “top down” implementation instead of “bottom up”

You can basically think of a statechart as a way of limiting what actions are available to be executed in certain states of the application. This concept is very old and was originally used to design machines where the user was exposed to all points of interaction, all buttons and switches, at any time. Statecharts would help make sure that at certain states certain buttons and switches would not operate.

A simple example of this is a Walkman. When the Walkman is in a **playing** state you should not be able to hit the **eject** button. On the web this might seem unnecessary as points of interaction is dynamic. We simply hide and/or disable buttons. But this is the exact problem. It is fragile. It is fragile because the UI implementation itself is all you depend on to prevent logic from running when it should not. A statechart is a much more resiliant way to ensure what logic can actually run in any given state.

In Overmind we talk about these statechart states as **transition states**.

## Get up and running

Install the separate package:

```
npm install overmind-statechart
```

## Defining a statechart

Let us imagine that we have a login flow. This login flow has 4 different **transition states**:

1. **LOGIN**. We are at the point where the user inserts a username and password
2. **AUTHENTICATING**. The user has submitted
3. **AUTHENTICATED**. The user has successfully logged in
4. **ERROR**. Something wrong happened

Let us do this properly and design this flow “top down”:

{% tabs %}
{% tab title="overmind/login/index.js" %}

```typescript
import { statechart } from 'overmind-statechart'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const loginChart = {
  initial: 'LOGIN',
  states: {
    LOGIN: {
      on: {
        changeUsername: null,
        changePassword: null,
        login: 'AUTHENTICATING'
      }
    },
    AUTHENTICATING: {
      on: {
        resolveUser: 'AUTHENTICATED',
        rejectUser: 'ERROR'
      }
    },
    AUTHENTICATED: {
      on: {
        logout: 'LOGIN'
      }
    },
    ERROR: {
      on: {
        tryAgain: 'LOGIN'
      }
    }
  }
}

export default statechart(config, loginChart)
```

{% endtab %}
{% endtabs %}

As you can see we have defined what transition states our login flow can be in and what actions we want available to us in each transition state. If the action points to **null** it means we stay in the same transition state. If it points to an other transition state, the execution of that action will cause that transition to occur.

Since our initial state is **LOGIN**, a call to actions defined in the other transition states would simply be ignored.

{% hint style="info" %}
You might expect actions to throw an error if they are called, but not allowed to do so. This is not the case with statecharts. During development you will get a warning when this happens, but in production absolutely nothing happens. Hitting a submit button multiple times might be perfectly okay, but after the first submit the chart moves to a new state, preventing any further execution of logic on the following submits.
{% endhint %}

## Transitions

If you are familiar with the concept of statemachines you might ask the question: *“Where are the transitions?”*. In Overmind we use actions to define transitions instead of having explicit transition types. That means you think about statecharts in Overmind as:

```
TRANSITION STATE -> ACTION -> NEW TRANSITION STATE
```

as opposed to:

```
TRANSITION STATE -> TRANSITION TYPE -> { NEW TRANSITION STATE, ACTION }
```

This approach has three benefits:

1. It is more explicit in the definition that a transition state configures what actions are available
2. When typing your application the actions already has a typed input, which would not be possible with a generic **transition** action
3. It is simpler concept both in code and for your brain

What to take notice of is that the **action** causing the transition is run before the transition actually happens. That means the action runs in the context of the current transition state and any synchronous calls to another action will obey its rules. If the action does something asynchronous, like doing an HTTP request, the transition will be performed and the asynchronous logic will run in the context of the new transition state.

```typescript
const myTransitionAction = async ({ actions }) => {
  // I am still in the current transition state
  actions.someOtherAction()

  await Promise.resolve()

  // I am in the new transition state
  actions.someOtherAction()
}
```

## Nested statecharts

With a more complicated UI we can create nested statecharts. An example of this would be a workspace UI with different tabs. You only want to allow certain actions when the related tab is active. Let us explore an example:

{% tabs %}
{% tab title="overmind/dashboard/index.js" %}

```typescript
import { statechart } from 'overmind-statechart'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const issuesChart = {
  initial: 'LOADING',
  states: {
    LOADING: {
      entry: 'fetchIssues',
      exit: 'abortFetchIssues',
      on: {
        resolveIssues: 'LIST',
        rejectIssues: 'ERROR'
      }
    },
    LIST: {
      on: {
        toggleIssueCompleted: null
      }
    },
    ERROR: {
      on: {
        retry: 'LOADING'
      }
    },
  }
}

const projectsChart = {
  initial: 'LOADING',
  states: {
    LOADING: {
      entry: 'fetchProjects',
      exit: 'abortFetchProjects',
      on: {
        resolveIssues: 'LIST',
        rejectIssues: 'ERROR'
      }
    },
    LIST: {
      on: {
        expandAttendees: null
      }
    },
    ERROR: {
      on: {
        retry: 'LOADING'
      }
    },
  }
}

const dashboardChart = {
  initial: 'ISSUES',
  states: {
    ISSUES: {
      on: {
        openProjects: 'PROJECTS'
      },
      chart: issuesChart
    },
    PROJECTS: {
      on: {
        openIssues: 'ISSUES'
      },
      chart: projectsChart
    }
  }
}

export default statechart(config, dashboardChart)
```

{% endtab %}
{% endtabs %}

What to take notice of in this example is that all chart states has its own **chart** property, which allows them to be nested. The nested charts has access to the same actions and state as the parent chart.

In this example we also took advantage of the **entry** and **exit** hooks of a transition state. These also points to actions. When a transition is made into the transition state, the **entry** will run. This behavior is nested. When an **exit** hook exists and a transition is made away from the transition state, it will also run. This behavior is also nested of course.

## Parallel statecharts

It is also possible to define your charts in a parallel manner. You do this by simply using an object of keys where the key represents an ID of the chart. The **chart** property on a transition state allows the same. Either a single chart or an object of multiple charts where the key represents an ID of the chart.

```typescript
export default statechart(config, {
  issues: issuesChart,
  projects: projectsChart
})
```

## Conditions

In our chart above we let the user log in even though there is no **username** or **password**. That seems a bit silly. In statecharts you can define conditions. These conditions receives the state of the configuration and returns true or false.

{% tabs %}
{% tab title="overmind/login/index.js" %}

```typescript
import { statechart } from 'overmind-statechart'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const loginChart = {
  initial: 'LOGIN',
  states: {
    LOGIN: {
      on: {
        changeUsername: null,
        changePassword: null,
        login: {
          target: 'AUTHENTICATING',
          condition: state => Boolean(state.username && state.password)
        }
      }
    },
    ...
  }
}

export default statechart(config, loginChart)
```

{% endtab %}
{% endtabs %}

Now the **login** action can only be executed when there is a username and password inserted, causing a transition to the new transition state.

## State

Our initial state defined for this configuration is:

{% tabs %}
{% tab title="overmind/login/state.js" %}

```typescript
export const state = {
  username: '',
  password: '',
  user: null,
  authenticationError: null
}
```

{% endtab %}
{% endtabs %}

As you can see we have no state indicating that we have received an error, like **hasError**. We do not have **isLoggingIn** either. There is no reason, because we have our transition states. That means the configuration is populated with some additional state by the statechart. It will actually look like this:

```typescript
{
  username: '',
  password: '',
  user: null,
  authenticationError: null,
  states: [['CHART', 'LOGIN']],
  actions: {
    changeUsername: true,
    changePassword: true,
    login: false,
    logout: false,
    tryAgain: false
  }
}
```

The **states** state is the current transition states. It is defined as an array of arrays. This indicates that we can have parallel and nested charts. The **CHART** symbol in the array indicates that you have defined an immediate chart. If you rather defined parallel charts you would define your own ids.

The **actions** state is a derived state. That means it automatically updates based on the current state of the chart. This is helpful for your UI implementation. It can use it to disable buttons etc. to help the user understand when certain actions are possible.

### Identifying states <a href="#statecharts-identifying-states" id="statecharts-identifying-states"></a>

There is also a third derived state called **matches**. This derived state returns a function that allows you to figure out what state you are in. This is also the API you use in your components to identify the state of your application:[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/guide/statecharts/matches.ts.ts)

```typescript
state.login.matches({
  LOGIN: true
})
```

You can also do more complex matches related to parallel and nested charts:[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/guide/statecharts/matches_multiple.ts.ts)

```typescript
// Nested
const isSearching = state.dashboard.matches({
  LIST: {
    search: {
      SEARCHING: true
    }
  }
})

// Parallel
const isDownloadingAndUploading = state.files.matches({
  download: {
    LOADING: true
  },
  upload: {
    LOADING: true
  }
})

// Complex match
const isOnlyDownloading = state.files.matches({
  download: {
    LOADING: true
  },
  upload: {
    LOADING: false
  }
})
```

### Actions <a href="#statecharts-actions" id="statecharts-actions"></a>

Our actions are defined something like:

{% tabs %}
{% tab title="overmind/login/actions.js" %}

```typescript
export const changeUsername = ({ state }, username) => {
  state.login.username = username
}

export const changePassword = ({ state }, password) => {
  state.login.password = password
}

export const login = ({ state, actions, effects }) => {
  try {
    const user = await effects.api.login(state.username, state.password)
    actions.login.resolveUser(user)
  } catch (error) {
    actions.login.rejectUser(error)
  }
}

export const resolveUser = ({ state }, user) => {
  state.login.user = user
}

export const rejectUser = ({ state }, error) => {
  state.login.authenticationError = error.message
}

export const logout = ({ effects }) => {
  effects.api.logout()
}

export const tryAgain = () => {}
```

{% endtab %}
{% endtabs %}

What to take notice of here is that with traditional Overmind we would most likely just set the **user** or the **authenticationError** directly in the **login** action. That is not the case with statcharts because our actions are the triggers for transitions. That means whenever we want to deal with transitions we create an action for it, even completely empty actions like **tryAgain**. This simplifies our chart definition and also we avoid having a generic **transition** action that would not be typed in TypeScript.

Now these two charts would operate individually. This is also the case for the **chart** property on the states of a chart.

## Devtools

The Overmind devtools understands statecharts. That means you are able to get an overview of available statecharts and even manipulate them directly in the devtools.

![](/files/-LyeAtF5_zJ45kWzFpgY)

You will see what transition states and actions are available, and active, within each of them. You can click any active action to select it and click again to execute, or insert at payload at the top before execution.

## Typescript

To type a statechart you use the **Statechart** type:

{% tabs %}
{% tab title="overmind/someNamespace/index.ts" %}

```typescript
import { Statechart, statechart } from 'overmind-statechart'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const someChart: Statechart<typeof config, {
  FOO: void
  BAR: void
}> = {
  initial: 'FOO',
  states: {
    FOO: {},
    BAR: {}
  }
}

export default statechart(config, someChart)
```

{% endtab %}
{% endtabs %}

The **void** type just defines that there are no nested charts. All the states and points of inserting an action name is now typed. Also the **condition** callback is typed. Even the **matches** API is typed correctly.

### Nested chart

{% tabs %}
{% tab title="overmind/someNamespace/index.ts" %}

```typescript
import { Statechart, statechart } from 'overmind-statechart'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const someNestedChart: Statechart<typeof config, {
  NESTED_FOO: void
  NESTED_BAR: void
}> = {
  initial: 'NESTED_FOO',
  states: {
    NESTED_FOO: {},
    NESTED_BAR: {}
  }
}

const someChart: Statechart<typeof config, {
  FOO: typeof someNestedChart
  BAR: void
}> = {
  initial: 'FOO',
  states: {
    FOO: {
      chart: someNestedChart
    },
    BAR: {}
  }
}

export default statechart(config, someChart)
```

{% endtab %}
{% endtabs %}

## Summary

The point of statecharts in Overmind is to give you an abstraction over your configuration that ensures the actions can only be run in certain states. Just like operators you can choose where you want to use it. Maybe only one namespace needs a statechart, or maybe you prefer using it on all of them. The devtools has its own visualizer for the charts, which allows you to implement and test them without implementing any UI.w

## API

### statechart

The factory function you use to wrap an Overmind configuration. You add one or multiple charts to the configuration, where the key is the *id* of the chart.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {}> = {}

export default statechart(config, chart)
```

### initial

Define the initial state of the chart. When a parent chart enters a transition state, any nested chart will move to its initial transition state.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
}> = {
  initial: 'STATE_A'
}

export default statechart(config, chart)
```

### states

Defines the transition states of the chart. The chart can only be in one of these states at any point in time.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {},
    STATE_B: {}
  }
}

export default statechart(config, chart)
```

### entry

When a transition state is entered you can optionally run an action. It also runs if it is the initial state.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      entry: 'someActionName'
    },
    STATE_B: {}
  }
}

export default statechart(config, chart)
```

{% hint style="info" %}
If you want to transition to a new state using an **entry**, you are free to call the action causing that transition from the **entry** action.
{% endhint %}

### exit

When a transition state is changed, any exit defined in current transition state will be run first. Nested charts in a transition state with an exit defined will run before parents.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      entry: 'someActionName',
      exit: 'someOtherActionName'
    },
    STATE_B: {}
  }
}

export default statechart(config, chart)
```

### on

Unlike traditional statecharts Overmind uses its actions as transition types. This keeps a cleaner chart definition and when using Typescript the actions will have correct typing related to their payload. The actions defined are the only actions allowed to run. They can optionally lead to a new transition state, even conditionally lead to a new transition state.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      on: {
        // Allow execution, but stay on this transition state
        someAction: null,

        // Move to new transition state when executed
        someOtherAction: 'STATE_B',

        // Conditionally move to a new transition state
        someConditionalAction: {
          target: 'STATE_B',
          condition: state => state.isTrue
        }
      }
    },
    STATE_B: {}
  }
}

export default statechart(config, chart)
```

### nested

A nested statechart will operate within its parent transition state. The means when the parent transition state is entered or exited any defined **entry** and **exit** actions will be run. When the parent enters its transition state the **initial** state of the child statechart(s) will be activated.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const nestedChart: Statechart<typeof config, {
  FOO: void
  BAR: void
}> = {
  initial: 'FOO',
  states: {
    FOO: {
      on: {
        transitionToBar: 'BAR'
      }
    },
    BAR: {
      on: {
        transitionToFoo: 'FOO'
      }
    }
  }
}

const chart: Statechart<typeof config, {
  STATE_A: typeof nestedChart
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      on: {
        transitionToStateB: 'STATE_B'
      },
      chart: nestedChart
    },
    STATE_B: {
      on: {
        transitionToStateA: 'STATE_A'
      }
    }
  }
}

export default statechart(config, chart)
```

### parallel

Multiple statecharts will run in parallel. Either for the factory configuration or nested charts. You can add the same chart multiple times behind different ids.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      on: {
        transitionToStateB: 'STATE_B'
      }
    },
    STATE_B: {
      on: {
        transitionToStateA: 'STATE_A'
      }
    }
  }
}

export default statechart(config, {
  chartA: chart,
  chartB: chart
})
```

{% hint style="info" %}
Also the nested **chart** property of charts can contain parallel charts
{% endhint %}

### matches

The matches API is used in your components to identify what state your charts are in. It is accessed on the **state**.

```typescript
// Given that you have added statecharts to the root configuration
state.matches({
  STATE_A: true
})

// Nested chart
state.matches({
  STATE_A: {
    FOO: true
  }
})

// Parallel
state.matches({
  chartA: {
    STATE_A: true
  },
  chartB: {
    STATE_B: true
  }
})

// Negative check
state.matches({
  chartA: {
    STATE_A: true
  },
  chartB: {
    STATE_B: false
  }
})
```


# Using state machines

The Overmind state machines is heavily inspired by [XState](https://xstate.js.org/) and [Davids](https://twitter.com/DavidKPiano) evangelism of bringing this old idea to life in the JavaScript ecosystem. Typically state machines are explained with very specific concepts like street lights, timers or similar "machine like" concepts. For Overmind it was important that this concept could be used to describe the overall state of the application. This was a huge challenge and required several iterations, but we found a concept that holds the idea true and makes it a practical and optional way to manage your state. Use it for your whole application or use it for specific scenarios.

{% hint style="info" %}
The state machine API is designed for use with **TypeScript**. The reason is that the complexity of transition state matching is best expressed using [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining), which is not yet available in plain JavaScript.
{% endhint %}

## Creating a state machine

To understand the benefit of a state machine we have to use a very specific example. One such example that is typical for any application is authentication. Typically in Overmind you would define this as:

```typescript
type State = {
  isAuthenticating: boolean
  user: { username: string } | null
  signedOutReason: string | null
}

export const state: State = {
  isAuthenticating: true,
  user: null,
  signedOutReason: null
}
```

You would use the existence of the **user** to determine if you are actually authenticated or not. This *works\*\*,\*\** but it does not describe the states of your application explicitly. If you rather describe this state as:

```typescript
type State = {
  current: 'AUTHENTICATING'
} | {
  current: 'AUTHENTICATED'
  user: { username: string }
} | {
  current: 'UNAUTHENTICATED'
  signedOutReason: string
}

export const state: State = {
  current: 'AUTHENTICATING'
}
```

Now we are describing what states our application can actually be in, and what other state is available at that time.

State machines does not only help us describe explicit states, they act as a translator between the effects of the outside world and the state of your application. It basically ensures that whatever happens "out there" the state machine will ensure that your state is valid.

You express this by mapping **events** to **state changes**.

```typescript
type User = { username: string }

type States =
  | {
    current: 'AUTHENTICATING'
  }
  | {
    current: 'AUTHENTICATED'
    user: User
  }
  | {
    current: 'UNAUTHENTICATED'
    signedOutReason: string
  }

type Events = 
  | {
    type: 'SIGNING_IN'
  }
  | {
    type: 'SIGNED_IN'
    data: User
  }
  | {
    type: 'SIGNED_OUT'
    data: string
  }

export const auth = statemachine<States, Events>({
  SIGNING_IN: (state) => {
    if (state.current === 'UNAUTHENTICATED') {
      return { current: 'AUTHENTICATING' }
    }
  },
  SIGNED_IN: (state, user) => {
    if (state.current === 'AUTHENTICATING') {
      return { current: 'AUTHENTICATED', user }
    }
  },
  SIGNED_OUT: (state, signedOutReason) => {
    if (state.current === 'AUTHENTICATED') {      
      return { current: 'UNAUTHENTICATED', signedOutReason }
    }
  }
})
```

In the example above we are are dealing with three events. For each event we check the current state of the machine to see if we want to deal with it at all. When we decide to deal with an event we can change any of the state, for example using **data** from the event. Then we can optionally return a new **current** transition state, with the required state for that transition state to be valid.

What we have effectively done now is ensure that when these events happens we always deal with them correctly. It is not the event that decides what should happen, it is the machine that decides it based on one of your explicitly set states.

## Instantiating a machine

To actually use the machine as part of your state you need to **create** it.

```javascript
import { auth } from './state'
import * as actions from './actions'

const config = {
  state: auth.create({
    current: 'AUTHENTICATING'
  })
}
```

By explicitly instantiating the machine you are allowed to start it in different transition states and also give preset state if necessary. You will see this becomes beneficial later when nesting machines.

## Sending events

Instead of explicitly changing the state, you send an **event**. The events is handled by the state machine and it will ensure that it is valid before moving on. That means when you change from **AUTHENTICATING** to **AUTHENTICATED** you would express it something like:

```javascript
export const authChanged = ({ state }, user) => {
  if (user) {
    state.send('SIGNED_IN', user)
  } else {
    state.send('SIGNED_OUT')
  }
}
```

When sending the **SIGNED\_IN** event we also provide the **user**. The current transition state of the machine is what decides if the user is set or not.

## Guarding effects

Now, your state machine is in charge of how it acts on events coming form the outside world, but you might also want the outside world to react to changes in your state machine. So imagine related to transitioning into a state you wanted to change the title of the page. To ensure this logic only runs when your application actually transitions into the **UNAUTHENTICATED** or **AUTHENTICATED** state we can check if the machine actually is in this state after sending it a message.

```javascript
export const authChanged = ({ state, effects }, user) => {
  if (user && state.send('SIGNED_IN', user).matches('AUTHENTICATED')) {
    effects.browser.setTitle('Logged in')
  } else if (state.send('SIGNED_OUT').matches('UNAUTHENTICATED')) {
    effects.browser.setTitle('Logged out')
  }
}
```

## Base state

Let us introduce a new machine, a **todos** machine.

```typescript
import { Statemachine } from 'overmind'

type Todo = { title: string, completed: boolean }

type States = 
 | {
   current: 'LOADING'
 }
 | {
   current: 'LIST'
 }

 type BaseState {
   list: Todo[]
 }

type Events =
  | {
    type: 'TODOS_LOADED',
    data: Todo[]
  }
  | {
    type: 'TODO_ADDED',
    data: Todo
  }

export type TodosMachine = Statemachine<States, Events, BaseState>

export const todos = statemachine<States, Events, BaseState>({
  TODOS_LOADED: (state, todos) => {
    if (state.current === 'LOADING') {      
      return { current: 'LIST', todos }
    }
  },
  TODO_ADDED: (state, todo) => {
    if (state.current === 'LIST') {
      state.list.push(todo)
    }
  }
})
```

In this simple example we introduced a todos machine that starts in a **LOADING** state and will at some point transition into a **LIST** state when the initial todos has been loaded. The machine introduces the concept of **base state**. That means state that is available no matter what transition state the machine is in. The purpose of **base state** is that it simplifies typing and the machine will also automatically remove state related to the current transition state, when transitioning to a new state. In the example above the **user** and the **signedOutReason** is deleted when moving out of **AUTHENTICATED** state.

## Nesting state machines

One of the goals of the Overmind implementation of state machines is that the machines becomes a natural part of your state tree. You can define them wherever you would normally define a value. That means you can create nested machines.

```typescript
import { TodosMachine, todos } from './Todos'

type States =
  | {
    current: 'AUTHENTICATING'
  }
  | {
    current: 'AUTHENTICATED'
    user: User
    todos: TodosMachine
  }
  | {
    current: 'UNAUTHENTICATED'
    signedOutReason: string
  }

type Events = {...}

export const auth = statemachine<States, Events>({
  SIGNING_IN: (state) => {
    if (state.current === 'UNAUTHENTICATED') {
      return { current: 'AUTHENTICATING' }
    }
  },
  SIGNED_IN: (state, user) => {
    if (state.current === 'AUTHENTICATING') {      
      return {
        current: 'AUTHENTICATED',
        user,
        todos: todos.create({ current: 'LOADING' }, { todos: [] })
      }
    }
  },
  SIGNED_OUT: (state, signedOutReason) => {
    if (state.current === 'AUTHENTICATED') {      
      return { current: 'UNAUTHENTICATED', signedOutReason }
    }
  }
})
```

Note that the **base state** of the **todos** is passed as a second argument.

Now we can go back to our authentication logic and introduce the loading of our todos.

```javascript
export const authChanged = async ({ state, effects }, user) => {
  if (user && state.send('SIGNED_IN', user).matches('AUTHENTICATED')) {
    const todos = await effects.api.getTodos()
    state.matches('AUTHENTICATED')?.todos.send('TODOS_LOADED', todos)
  } else if (state.send('SIGNED_OUT').matches('UNAUTHENTICATED')) {
    effects.browser.setTitle('Logged out')
  }
}
```

You will notice that with nested machines you will be using **matches** and optional chaining quite a bit. The reason simply being that you will always have to ensure that your machines are in the correct transition state before interacting with any of its state and nested machines.

## Identifying current state in components

All state machines has a **current** property. This can be used to evaluate what should be rendered, here shown with React:

```javascript
export const App = () => {
  const { state } = useOvermind()

  if (state.current === 'AUTHENTICATING') {
    return <div>Loading...</div>
  }

  if (state.current === 'AUTHENTICATED') {
    return <div>You are not authenticated</div>
  }

  return <div>Hello there!</div>
}
```

When dealing with nested machines you will have to do nested checks. This might seem unnecessary, maybe you loaded the **Todos** component only when the parent is in **AUTHENTICATED** state, but components can be moved and loaded anywhere, so this ensures it behaves exactly like we want it to.

```typescript
export const Todos = () => {
  const { state } = useOvermind()

  if (!state.current === 'AUTHENTICATED') return null

  return (
    <div>
      {state.todos.current === 'LOADING' ? 'Loading...' : null}
      <ul>{state.todos.list.map(() => ...)}</ul>
    </div>
  )
}
```

## Strict mode

In strict mode you are not able to change state in actions, you explicitly have to use a state machine transitions through the **send** API to make state changes.

```javascript
const overmind = createOvermind(config, {
  strict: true
})
```

```javascript
export const authChanged = ({ state }, user) => {
  // This would throw an error 
  state.user = user
}
```


# Connecting components

Now that you have defined a state describing your application, you probably want to transform that state into a user interface. There are many ways to express this and Overmind supports the most popular libraries and frameworks for doing this transformation, typically called a view layer. You can also implement a custom view layer if you want to.

By installing the view layer of choice you will be able to connect it to your Overmind instance, exposing its state, actions and effects.

{% tabs %}
{% tab title="React" %}
{% code title="App.jsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../../overmind'

const App = () => {
  const { state } = useOvermind()

  if (state.isLoading) {
    return <div>Loading app...</div>
  }

  return <h1>My awesome app</h1>
}

export default App
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="app.component.ts" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
<div *track>
  <div *ngIf="state.isLoading">
    Loading app...
  </div>
  <h1 *ngIf="!state.isLoading">
    My awesome app
  </h1>
</div>
  `
})
export class App {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <div v-if="state.isLoading">
    Loading app...
  </div>
  <h1 v-else>My awesome app</h1>
</template>
```

{% endtab %}
{% endtabs %}

In this example we are accessing the **isLoading** state. When this component renders and this state is accessed, Overmind will automatically understand that this component is interested in this exact state. It means that whenever the value is changed, this component will render again.

## State

When Overmind detects that the **App** component is interested in our **isLoading** state, it is not looking at the value itself, it is looking at the path. The component is pointed to **state.isLoading** which means that when a mutation occurs on that path in the state, the component will render again. Since the value is a boolean value this can only happen when **isLoading** is replaced or removed. The same goes for strings and numbers as well. We do not say that we mutate a string, boolean or a number. We mutate the object or array that holds those values.

The story is a bit different if the state value is an object or an array. These values can not only be replaced and removed, they can also mutate themselves. An object can have keys added or removed. An array can have items added, removed and even change the order of items. Overmind knows this and will notify components respectively. Let us look at how Overmind treats the following scenarios to get a better understanding.

### Arrays

When we just access an array in a component it will re-render if the array itself is replaced, removed or we do a mutation to it. That would mean we push a new item to it, we splice it or sort it.

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const List = () => {
  const { state } = useOvermind()

  return (
    <h1>{state.items}</h1>
  )
}

export default List
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-list',
  template: `
  <h1 *track>{{state.items}}</h1>
  `
})
export class List {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <h1>{{ state.items }}</h1>
</template>
```

{% endtab %}
{% endtabs %}

But what happens if we iterate the array and access a property on each item?

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const List = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.items.map(item => 
        <li key={item.id}>{item.title}</li>
      )}
    </ul>
  )
}

export default App
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-list',
  template: `
  <ul>
    <li *ngFor="let item of state.items;trackby: trackById">
      {{item.title}}
    </li>
  </ul>
  `
})
export class List {
  state = this.store.select()
  constructor(private store: Store) {}
  trackById(index, item) {
    return item.id
  }
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <ul>
    <li v-for="item in state.items" :key="item.id">
      {{ item.title }}
    </li>
  </ul>
</template>
```

{% endtab %}
{% endtabs %}

The benefit now is that the **List** component will only render when there is a change to the actual list, while each individual **Item** component will render when its respective title changes.

### Objects

Objects are similar to arrays. If you access an object you track if that object is replaced or removed. As with arrays, you can mutate the object itself. When you add, replace or remove a key from the object, it is considered a mutation of the object. It means that if you just access the object, the component will render if any keys are added, replaced or removed.

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const List = () => {
  const { state } = useOvermind()

  return (
    <h1>{state.items}</h1>
  )
}

export default List
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-list',
  template: `
  <h1>{{state.items}}</h1>
  `
})
export class List {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <h1>{{ state.items }}</h1>
</template>
```

{% endtab %}
{% endtabs %}

And just like an array you can iterate the object keys to pass items to a child component for optimal rendering.

{% tabs %}
{% tab title="React" %}
{% code title="Item.jsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const Item = ({ item }) => {
  useOvermind()

  return (
    <li>{item.title}</li>
  )
}

export default Item
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="item.component.ts" %}

```typescript
import { Component Input } from '@angular/core';
import { Item } from '../overmind/state'

@Component({
  selector: 'app-list-item',
  template: `
  <li *track>
    {{item.title}}
  </li>
  `
})
export class List {
  @Input() item: Item;
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="Item.vue" %}

```typescript
<template>
  {{ item.title }}
</template>
<script>
export default {
  name: 'Item',
  props: ['item']
}
</script>
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="React" %}
{% code title="List.jsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'
import Item from './Item'

const List = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {Object.keys(state.items).map(key => 
        <Item key={key} item={state.items[key]} />
      )}
    </ul>
  )
}

export default List
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="list.component.ts" %}

```typescript
import { Component Input } from '@angular/core';
import { Item } from '../overmind/state'

@Component({
  selector: 'app-list-item',
  template: `
  <li *track>
    {{item.title}}
  </li>
  `
})
export class List {
  @Input() item: Item;
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="List.vue" %}

```typescript
<template>
  <ul>
    <li is="Item" v-for="item in state.items" :item="item" :key="item.id" />
  </ul>
</template>
<script>
import Item from './Item'

export default {
  name: 'List',
  components: {
    Item,
  },
}
</script>
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Actions

All the actions defined in the Overmind application are available to connected components.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const toggleAwesomeApp = ({ state }) =>
  state.isAwesome = !state.isAwesome
```

{% endtab %}
{% endtabs %}

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const App = () => {
  const { actions } = useOvermind()

  return (
    <button onClick={actions.toggleAwesomeApp}>
      Toggle awesome
    </button>
  )
}

export default App
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
  <button (click)="actions.toggleAwesomeApp()">
    Toggle awesome
  </button>
  `
})
export class App {
  actions = this.store.actions
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <button @click="actions.toggleAwesomeApp()">
    Toggle awesome
  </button>
</template>
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
If you need to pass multiple values to an action, you should rather use an **object** instead.
{% endhint %}

## Reactions

Sometimes you want to make something happen inside a component related to a state change. This is typically doing some manual work on the DOM. When you connect a component to Overmind it also gets access to **reaction**. This function allows you to subscribe to changes in state, mutations as we call them.&#x20;

This example shows how you can scroll to the top of the page every time you change the current article of the app.

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

```typescript
import * as React from 'react'
import { useOvermind } from '../../overmind'

const Article = () => {
  const { reaction } = useOvermind()

  React.useEffect(() => reaction(
    (state) => state.currentArticle,
    () => document.querySelector('#app').scrollTop = 0 
  ), [])

  return <article />
}

export default Article
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
  <article></article>
  `
})
export class App {
  disposeEffect: () => void
  constructor(private store: Store) {}
  ngOnInit() {
    this.disposeReaction = this.store.reaction(
      (state) => state.currentArticle,
      () => document.querySelector('#app').scrollTop = 0   
    )
  }
  ngOnDestroy() {
    this.disposeReaction()
  }
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <article></article>
</template>
<script>
export default {
  name: 'Article',
  mounted() {
    this.disposeReaction = this.overmind.reaction(
      (state) => state.currentArticle,
      () => document.querySelector('#app').scrollTop = 0   
    })
  }
  destroyed() {
    this.disposeReaction()
  }
}
</script>
```

{% endtab %}
{% endtabs %}

## Effects

Any effects you define in your Overmind application are also exposed to the components. They can be found on the property **effects**. It is encouraged that you keep your logic inside actions, but you might be in a situation where you want some other relationship between components and Overmind. A shared effect is the way to go.


# Managing lists

Why do we even have a guide to managing lists? Well, lists are a type of state that differ from other types of state. Both from the perspective of the state itself, but also transforming that state into UI.

{% hint style="info" %}
The discussion of lists is not specific to Overmind and there are no limitations on how you want to approach this. This guide is rather to help you think about how you structure entities (data with an id) to optimally access and render them.
{% endhint %}

## Defining the state

When we want to render a list of something we want an **array**. This is the data structure we instinctively go to as it basically is a list. But arrays are rarely the way you want to store the actual data of the list.

If your list consists of posts, these posts are most likely entities from the server which are unique, and have a unique id. A data structure that better manages uniqueness is an **object**.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/guide/managinglists/object.ts)

```typescript
{
  "uniqueId1": {},
  "uniqueId2": {},
  "uniqueId3": {}
}
```

Another benefit from using an object is that you have a direct reference to the entity by using its id. No need to iterate an array to find what you are looking for. So this is a good rule of thumb: if the state you are defining has unique identifiers they should most likely be stored as an object, not an array.

But we still want to use an array when we transform the state into a UI. Let us see what we can do about that.

## Derive to a list

In Overmind it is encouraged that you derive these dictionaries of entities to a list by deriving the state. The most simple way to do this is:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  posts: {}
  postsList: state => Object.values(state.posts)
}
```

{% endtab %}
{% endtabs %}

Now when we point to **state.postsList** we get an array of posts. What is important to remember here is that we do not create the list again whenever we point to this state value. It is only run again if there is a change to the referenced posts’ state.

## Sorting

Now we have optimally stored our posts in a dictionary for easy access by id. We have also created a derived state which converts this dictionary to an array whenever the source dictionary changes. Though most likely you want to sort the list. Typically lists are sorted chronologically and our posts item has a **datetime** field.

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  posts: {}
  postsList: state =>
    Object.values(state.posts)
      .sort((postA, postB) => {
        if (postA.datetime > postB.datetime) {
          return 1
        } else if (postA.datetime < postB.datetime) {
          return -1
        }

        return 0
      })
}
```

{% endtab %}
{% endtabs %}

There we go, our posts are now shown chronologically. But maybe we only want to show some of the posts that are available? Maybe the list should only contain the ten latest entries?

## Filtering

To limit the number of posts shown we can create a new state and use it inside our derived state to limit the number of results.

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { Derive } from 'overmind'

export type Post {
  id: string
  title: string
  body: string
  datetime: number
}

export type State = {
  posts: { [id: string] : Post }
  showCount: number
  postsList: Derive<State, Post[]>
}

export const state: State = {
  posts: {},
  showCount: 10,
  postsList: state =>
    Object.values(state.posts)
      .sort((postA, postB) => {
        if (postA.datetime > postB.datetime) {
          return 1
        } else if (postA.datetime < postB.datetime) {
          return -1
        }

        return 0
      })
      .slice(0, state.showCount)
}
```

{% endtab %}
{% endtabs %}

Now if we change the **showCount** state our derived list will indeed update.

## Rendering lists

So now let’s look at how we would consume such a list. Let us look at a straightforward example first:

{% tabs %}
{% tab title="React" %}
{% code title="components/App.tsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const Posts: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.postsList.map(post => 
        <li key={post.id}>{post.title}</li>
      )}
    </ul>
  )
}

export default App
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="components/posts.component.ts" %}

```typescript
import { Component } from '@angular/core';
import { connect } from '../overmind'

@Component({
  selector: 'app-posts',
  template: `
  <ul>
    <li *ngFor="let post of overmind.state.postsList;trackby: trackById">
      {{post.title}}
    </li>
  </ul>
  `
})
@connect()
export class List {
  trackById(index, post) {
    return post.id
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="components/Posts.vue" %}

```typescript
<template>
  <ul>
    <li v-for="post in state.postsList" :key="post.id>
      {{ post.title }}
    </li>
  </ul>
</template>
```

{% endcode %}
{% endtab %}
{% endtabs %}

Now this approach will work perfectly fine. The component will render the list and update it whenever it needs to. The only drawback with this approach is that any change to individual posts will also cause the component to render, specifically the **title** of a post since that is the only thing we are looking at. This is because this one component is looking at all the posts. We can optimize this by passing each post down to a child component:

{% tabs %}
{% tab title="React" %}
{% code title="components/Post.tsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'
import { Post as TPost } from '../overmind/state'

type Props = {
  post: TPost
}

const Post: React.FunctionComponent<Props> = ({ post }) => {
  // We still need to use the hook so that the component tracks
  // changes to the post
  useOvermind()

  return (
    <li>{post.title}</li>
  )
}

export default Post
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="components/post.component.ts" %}

```typescript
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
import { Post } from '../overmind/state'

@Component({
  selector: 'app-post',
  template: `
  <li *track>
    {{post.title}}
  </li>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class List {
  @Input() post: Post;
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="components/Post.vue" %}

```typescript
<template>
  <li>{{ post.title }}</li>
</template>
<script>
export {
  props: ['post']
}
</script>
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="React" %}
{% code title="components/Posts.tsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'
import Post from './Post'

const Posts: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.postsList.map(post => 
        <Post key={post.id} post={post} />
      )}
    </ul>
  )
}

export default Posts
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="components/posts.component.ts" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-posts',
  template: `
  <ul>
    <app-post
      *ngFor="let post of state.postsList;trackby: trackById"
      [post]="post"
    ></app-post>
  </ul>
  `
})
export class List {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="components/Posts.vue" %}

```typescript
<template>
  <ul>
    <post-component v-for="post in state.postsList" :post="post" :key="post.id"></post-component>
  </ul>
</template>
<script>
import PostComponent from './Post'

export default {
  name: 'Posts',
  components: {
    PostComponent,
  },
}
</script>
```

{% endcode %}
{% endtab %}
{% endtabs %}

Now the **Posts** component only cares about changes to the list itself, while each **Post** component cares about its corresponding post title. It means that if the title of a post updates, only the component that actually cares about that post renders again. If the list itself changes only the **Posts** component will render.

### Summary <a href="#managing-lists-summary" id="managing-lists-summary"></a>

Managing lists has two considerations: defining how to store the data of the list, and how to actually render the list. It can be a good idea to store data entities with unique ids as a dictionary and rather use a **derived** state to produce the array itself. This gives you best of both worlds – easy lookup using the id, and a cached list that only updates when dependent state updates.


# State first routing

With Overmind you can use whatever routing solution your selected view layer provides. This will most likely intertwine routing state with your component state, which is something Overmind would discourage, but you know… whatever you feel productive in, you should use :-) In this guide we will look into how you can separate your router from your components and make it part of your application state instead. This is more in the spirit of Overmind and throughout this guide you will find benefits of doing it this way.

We are going to use [PAGE.JS](https://www.npmjs.com/package/page) as the router and we will look at a complex routing example where we open a page with a link to a list of users. When you click on a user in the list we will show that user in a modal with the URL updating to the id of the user. In addition we will present a query parameter that reflects the current tab inside the modal.

We will start with a simple naïve approach and then tweak our approach a little bit for the optimal solution.

## Set up the app

Before we go into the router we want to set up the application. We have some state helping us express the UI explained above. In addition we have three actions.

1. **showHomePage** tells our application to set the current page to *home*
2. **showUsersPage** tells our application to set the current page to *users* and fetches the users as well
3. **showUserModal** tells our application to show the modal by setting an id of a user passed to the action. This action will also handle the switching of tabs later.

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
import { Action, AsyncAction } from 'overmind'

export const showHomePage: Action = ({ state }) => {
  state.currentPage = 'home'
}

export const showUsersPage: AsyncAction = async ({ state, effects }) => {
  state.modalUser = null
  state.currentPage = 'users'
  state.isLoadingUsers = true
  state.users = await effects.api.getUsers()
  state.isLoadingUsers = false
}

export const showUserModal: AsyncAction<{ id: string }> = async ({ state, effects }, params) => {
  state.isLoadingUserDetails = true
  state.modalUser = await effects.api.getUserWithDetails(params.id)
  state.isLoadingUserDetails = false
}
```

{% endtab %}
{% endtabs %}

## Initialize the router

**Page.js** is pretty straightforward. We basically want to map a URL to trigger an action. To get started, let us first add Page.js as an effect and take the opportunity to create a custom API. When a URL triggers we want to pass the params of the route to the action linked to the route:

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import page from 'page'

// We allow void type which is used to define "no params"
type IParams = {
  [param: string]: string  
} | void

export const router = {
  initialize(routes: { [url: string]: (params: IParams) => void }) {
    Object.keys(routes).forEach(url => {
      page(url, ({ params }) => routes[url](params))
    })
    page.start()
  },
  open: (url: string) => page.show(url)
}
```

{% endtab %}
{% endtabs %}

Now we can use Overmind’s **onInitialize** to configure the router. That way the initial URL triggers before the UI renders and we get to set our initial state.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

const onInitialize: OnInitialize = ({ actions, effects }) => {
  effects.router.initialize({
    '/': actions.showHomePage,
    '/users': actions.showUsersPage,
    '/users/:id', actions.showUserModal
  })
}

export default onInitialize
```

{% endtab %}
{% endtabs %}

Take notice here that we are actually passing in the params from the router, meaning that the id of the user will be passed to the action.

## The list of users

When we now go to the list of users the list loads up and is displayed. When we click on a user the URL changes, our **showUser** action runs and indeed, we see a user modal.

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

```typescript
// components/App.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'
import Users from './Users'

const App: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <div className="container">
      <nav>
        <a href="/">Home</a>
        <a href="/users">Users</a>
      </nav>
      {state.currentPage === 'home' ? <h1>Hello world!</h1> : null}
      {state.currentPage === 'users' ? <Users /> : null}
    </div>
  )
}

export default App

// components/Users.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'
import UserModal from './UserModal'

const Users: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <div className="content">
      {state.isLoadingUsers ? (
        <h4>Loading users...</h4>
      ) : (
        <ul>
          {state.users.map(user => (
            <li key={user.id}>
              <a href={"/users/" + user.id}>{user.name}</a>
            </li>
          ))}
        </ul>
      )}
      {state.isLoadingUserDetails || state.modalUser ? <UserModal /> : null}
    </div>
  )
}

export default Users

// components/UserModal.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'

const UserModal: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <a href="/users" className="backdrop">
      <div className="modal">
        {state.isLoadingUserDetails ? (
          <h4>Loading user details...</h4>
        ) : (
          <>
            <h4>{state.modalUser.name}</h4>
            <h6>{state.modalUser.details.email}</h6>
            <nav>
              <a href={"/users/" + state.modalUser.id + "?tab=0"}>bio</a>
              <a href={"/users/" + state.modalUser.id + "?tab=1"}>address</a>
            </nav>
            {state.currentUserModalTabIndex === 0 ? (
              <div className="tab-content">{state.modalUser.details.bio}</div>
            ) : null}
            {state.currentUserModalTabIndex === 1 ? (
              <div className="tab-content">{state.modalUser.details.address}</div>
            ) : null}
          </>
        )}
      </div>
    </a>
  )
}

export default UserModal
```

{% endtab %}

{% tab title="Angular" %}

```typescript
// components/app.component.ts
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-component',
  template: `
  <div class="container" *track>
    <nav>
      <a href="/">Home</a>
      <a href="/users">Users</a>
    </nav>
    <h1 *ngIf="state.currentPage === 'home'">Hello world!</h1>
    <users-list *ngIf="state.currentPage === 'users'"></users-list>
  </div>
  `
})
export class AppComponent {
  state = this.store.select()
  constructor(private store: Store) {}
}

// components/users-list.component.ts
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'users-list',
  template: `
  <div class="content" *track>
    <h4 *ngIf="state.isLoadingUsers">Loading users...</h4>
    <ul *ngIf="!state.isLoadingUsers">
      <li *ngFor="let user of state.users;trackby: trackById">
        <a href={"/users/" + user.id}>{{user.name}}</a>
      </li>
    </ul>
    <user-modal *ngIf="state.isLoadingUserDetails || state.userModal"></user-modal>
  </div>
  `
})
export class UsersList {
  state = this.store.select()
  constructor(private store: Store) {}
  trackById(index, user) {
    return user.id
  }
}

// components/user-modal.component.ts
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'user-modal',
  template: `
  <a href="/users" class="backdrop">
    <div class="modal">
      <h4 *ngIf="state.isLoadingUserDetails">Loading user details...</h4>
      <div *ngIf="!state.isLoadingUserDetails">
        <h4>{{state.modalUser.name}}</h4>
        <h6>{{state.modalUser.details.email}}</h6>
        <nav>
          <a [href]="'/users/' + state.modalUser.id + '?tab=0'">bio</a>
          <a [href]="'/users/' + state.modalUser.id + '?tab=1'">address</a>
        </nav>
        <div
          *ngIf="state.currentUserModalTabIndex === 0"
          class="tab-content"
        >
          {{modalUser.details.bio}}
        </div>
        <div
          *ngIf="state.currentUserModalTabIndex === 1"
          class="tab-content"
        >
          {{modalUser.details.address}}
        </div>
      </div>
    </div>
  </a>
  `
})
export class UserModal {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
// components/App.vue
<template>
  <div class="container">
    <nav>
      <a href="/">Home</a>
      <a href="/users">Users</a>
    </nav>
    <h1 v-if="state.currentPage === 'home'">Hello world!</h1>
    <users-list v-if="state.currentPage === 'users'"></users-list>
  </div>
</template>

// components/UsersList.vue
<template>
  <div class="content">
    <h4 v-if="state.isLoadingUsers">Loading users...</h4>
    <ul v-else>
      <li v-for="user in state.users" :key="user.id">
        <a :href="'/users/' + user.id">{{ user.name }}</a>
      </li>
    </ul>
    <user-modal v-if="state.isLoadingUserDetails || state.userModal"></user-modal>
  </div>
</template>

// components/UserModal.vue
<template>
  <a href="/users" class="backdrop">
    <div class="modal">
      <h4 v-if="state.isLoadingUserDetails">Loading user details...</h4>
      <div v-else>
        <h4>{{ state.modalUser.name }}</h4>
        <h6>{{ state.modalUser.details.email }}</h6>
        <nav>
          <a :href="'/users/' + state.modalUser.id + '?tab=0'">bio</a>
          <a :href="'/users/' + state.modalUser.id + '?tab=1'">address</a>
        </nav>
        <div
          v-if="state.currentUserModalTabIndex === 0"
          class="tab-content"
        >
          {{ state.modalUser.details.bio }}
        </div>
        <div
          v-if="state.currentUserModalTabIndex === 1"
          class="tab-content"
        >
          {{ modalUser.details.address }}
        </div>
      </div>
    </div>
  </a>
</template>
```

{% endtab %}
{% endtabs %}

But what if we try to refresh now… we get an error. The router tries to run our user modal, but we are on the front page. The modal does not exist there. We want to make sure that when we open a link to a user modal we also go to the actual user list page.

## Composing actions

A straightforward way to solve this is to simply also change the page in the **showUserModal** action, though we would like the list of users to load in the background as well. The logic of **showUsers** might also be a lot more complex and we do not want to duplicate our code. When these scenarios occur where you want to start calling actions from actions, it indicates you have reached a level of complexity where a functional approach might be better. Let us look at how you would implement this both using a functional approach and a plain imperative one.

### Imperative approach

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
import { Action, AsyncAction } from 'overmind'
import { Page } from './types'

export const showHomePage: Action = ({ state }) => {
  state.currentPage = Page.HOME
}

export const showUsersPage: AsyncAction = async ({ state, effects }) => {
  state.currentPage = Page.USERS
  state.modalUser = null

  if (!Object.keys(state.users).length) {
    state.isLoadingUsers = true
    state.users = await effects.api.getUsers()
    state.isLoadingUsers = false
  }
}

export const showUserModal: AsyncAction<{ id: string }> = async ({ state, actions }, params) => {
  actions.showUsersPage()
  state.isLoadingUserDetails = true
  state.modalUser = await effects.api.getUserWithDetails(params.id)
  state.isLoadingUserDetails = false
}
```

{% endtab %}
{% endtabs %}

Going functional depends on complexity and even though the complexity has indeed increased, we can safely manage it using plain imperative code. Whenever we open a user modal we can simply just call the action that takes care of bringing us to the users page as well.

When running actions from within other actions like this it will be reflected in the devtool.

### Functional approach

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, mutate, filter } from 'overmind'
import { Page } from './types'

export const closeUserModal: <T>() => Operator<T> = () =>
  mutate(function closeUserModal({ state }) {
    state.modalUser = null
  })

export const setPage: <T>(page: Page) => Operator<T> = (page) =>
  mutate(function setPage({ state }) {
    state.currentPage = page
  })

export const shouldLoadUsers: <T>() => Operator<T> = () => 
  filter(function shouldLoadUsers({ state }) {
    return !Boolean(state.users.length)
  })

export const loadUsers: <T>() => Operator<T> = () => 
  mutate(async function loadUsers({ state, effects }) {
    state.isLoadingUsers = true
    state.users = await effects.api.getUsers()
    state.isLoadingUsers = false
  })

export const loadUserWithDetails: () => Operator<{ id: string }> = () => 
  mutate(async function loadUserWithDetails({ state, effects }, params) {
    state.isLoadingUserDetails = true
    state.modalUser = await effects.api.getUserWithDetails(params.id)
    state.isLoadingUserDetails = false
  })
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe } from 'overmind'
import { Page } from './types'
import * as o from './operators'

export const showHomePage: Operator = o.setPage(Page.HOME)

export const showUsersPage: Operator = pipe(
  o.setPage(Page.USERS),
  o.closeUserModal(),
  o.shouldLoadUsers(),
  o.loadUsers()
)

export const showUserModal: Operator<{ id: string }> = pipe(
  o.setPage(Page.USERS),
  o.loadUserWithDetails(),
  o.shouldLoadUsers(),
  o.loadUsers(),
)
```

{% endtab %}
{% endtabs %}

By splitting up all our logic into operators we were able to make our actions completely declarative and at the same time reuse logic across them. The *operators* file gives us maintainable code and the *actions* file gives us readable code.

We could actually make this better though. There is no reason to wait for the user of the modal to load before we load the users list in the background. We can fix this with the **parallel** operator. Now the list of users and the single user load at the same time.

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe, parallel } from 'overmind'
import { Page } from './types'
import * as o from './operators'

export const showHomePage: Operator<void> = o.setPage(Page.HOME)

export const showUsersPage: Operator<void> = pipe(
  o.setPage(Page.USERS),
  o.closeUserModal(),
  o.shouldLoadUsers(),
  o.loadUsers()
)

export const showUserModal: Operator<{ id: string }> = pipe(
  o.setPage(Page.USERS),
  parallel(
    o.loadUserWithDetails(),
    pipe(
      o.shouldLoadUsers(),
      o.loadUsers()
    ),
  )
)
```

{% endtab %}
{% endtabs %}

Now you are starting to see how the operators can be quite useful to compose flow. This flow is also reflected in the development tool of Overmind.

## The tab query param

**Page.js** also allows us to manage query strings, the stuff after the **?** in the url. Page.js does not parse it though, so we introduce a library which does just that, [QUERY-STRING](https://www.npmjs.com/package/query-string). With this we can update our router to also pass in any query params.

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import page from 'page'
import queryString from 'query-string'

type IParams = {
  [param: string]: string  
} | void

export const router = {
  initialize(routes: { [url: string]: (IParams) => void }) {
    Object.keys(routes).forEach(url => {
      page(url, ({ params, querystring }) => {
        const payload = Object.assign({}, params, queryString.parse(querystring))

        routes[url](payload)
      })
    })
    page.start()
  },
  open: (url: string) => page.show(url)
}
```

{% endtab %}
{% endtabs %}

### Imperative approach

We now also handle the received tab parameter and make sure that when we change tabs we do not load the user again. We only want to load the user when there is no existing user or if the user has changed.

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
import { Action, AsyncAction } from 'overmind'
import { Page } from './types'

export const showHomePage: Action = ({ state }) => {
  state.currentPage = Page.HOME
}

export const showUsersPage: AsyncAction = async ({ state, effects }) => {
  state.currentPage = Page.USERS
  state.modalUser = null

  if (!Object.keys(state.users).length) {
    state.isLoadingUsers = true
    state.users = await effects.api.getUsers()
    state.isLoadingUsers = false
  }
}

export const showUserModal: AsyncAction<{ id: string, tab: string }> = async ({ state, actions }, params) => {
  actions.showUsersPage()
  state.currentUserModalTabIndex = Number(params.tab)
  state.isLoadingUserDetails = true
  state.modalUser = await effects.api.getUserWithDetails(params.id)
  state.isLoadingUserDetails = false
}
```

{% endtab %}
{% endtabs %}

### Functional approach

Now we can add an operator which uses this **tab** query to set the current tab and then compose it into the action. We also add an operator to verify if we really should load a new user.

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, mutate, filter } from 'overmind'
import { Page } from './types'

export const closeUserModal: <T>() => Operator<T> = () =>
  mutate(function closeUserModal({ state }) {
    state.modalUser = null
  })

export const setPage: <T>(page: string) => Operator<T> = (page) =>
  mutate(function setPage({ state }) {
    state.currentPage = page
  })

export const shouldLoadUsers: <T>() => Operator<T> = () => 
  filter(function shouldLoadUsers({ state }) {
    return !Boolean(state.users.length)
  })

export const loadUsers: <T>() => Operator<T> = () => 
  mutate(async function loadUsers({ state, effects }) {
    state.isLoadingUsers = true
    state.users = await effects.api.getUsers()
    state.isLoadingUsers = false
  })

export const loadUserWithDetails: () => Operator<{ id: string }> = () => 
  mutate(async function loadUserWithDetails({ state, effects }, params) {
    state.isLoadingUserDetails = true
    state.modalUser = await effects.api.getUserWithDetails(params.id)
    state.isLoadingUserDetails = false
  })

export const shouldLoadUserWithDetails: <T>() => Operator<{ id: string }, T> = () => 
  filter(function shouldLoadUserWithDetails({ state }, params) {
    return !state.modalUser || state.modalUser.id !== params.id
  })

export const setCurrentUserModalTabIndex: <T>() => Operator<{ tab: string }, T> = () =>
  mutate(function setCurrentUserModalTabIndex({ state }, params) {
    state.currentUserModalTabIndex = Number(params.tab)
  })
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe, parallel } from 'overmind'
import { Page } from './types'
import * as o from './operators'

export const showHomePage: Operator = o.setPage(Page.HOME)

export const showUsersPage: Operator = pipe(
  o.setPage(Page.USERS),
  o.closeUserModal(),
  o.shouldLoadUsers(),
  o.loadUsers()
)

export const showUserModal: Operator<{ id: string, tab: string }> = pipe(
  o.setPage(Page.USERS),
  parallel(
    pipe(
      o.setCurrentUserModalTabIndex(),
      o.shouldLoadUserWithDetails(),
      o.loadUserWithDetails()
    ),
    pipe(
      o.shouldLoadUsers(),
      o.loadUsers()
    )
  )
)
```

{% endtab %}
{% endtabs %}

## Summary

With little effort we were able to build a custom “**application state first**“ router for our application. Like many common tools needed in an application, like talking to the server, localStorage etc., there are often differences in the requirements. And even more often you do not need the full implementation of the tool you are using. By using simple tools you can meet the actual requirements of the application more “head on” and this was an example of that.

We also showed how you can solve this issue with an imperative approach or go functional. In this example functional is probably a bit overkill as there is very little composition required. But if your application needed to use these operators many times in different configurations you would benefit more from it.


# Move to Typescript

You are here, great! This will be worth your time.


# Testing

Testing is a broad subject and everybody has an opinion on it. We can only show you how we think about testing in general and how to effectively write those tests for your Overmind app.&#x20;

The most important tests you can write are those who test how your application works when it is all put together, as close to the user experience as possible, so called E2E tests. Testing solutions like [CYPRESS.IO](https://www.cypress.io/) are a great way to do exactly that. You can read more about Cypress and integration testing with Overmind in [THIS ARTICLE](https://www.cypress.io/blog/2019/02/28/shrink-the-untestable-code-with-app-actions-and-effects/#).

You can also do **unit testing** of actions and effects. This will cover expected changes in state and that your side effects behave in a predictable manner. This is typically more important when you are not using Typescript.

## Structuring the app

When you write tests you will create many instances of a mocked version of Overmind with the configuration you have created. To ensure that this configuration can be used many times we have to separate our configuration from the instantiation of the actual app.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { IConfig } from 'overmind'
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

Now we are free to import our configuration without touching the application instance. Lets go!

## Testing actions

When testing an action you’ll want to verify that changes to state are performed as expected. To give you the best possible testing experience Overmind comes with a mocking tool called **createOvermindMock**. It takes your application configuration and allows you to run actions as if they were run from components.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPost = async ({ state, api }, id) {
  state.isLoadingPost = true
  try {
    state.currentPost = await api.getPost(id)
  } catch (error) {
    state.error = error
  }
  state.isLoadingPost = false
}
```

{% endtab %}
{% endtabs %}

You might want to test if a thrown error is handled correctly here. This is an example of how you could do that:

{% tabs %}
{% tab title="overmind/actions.test.js" %}

```typescript
import { createOvermindMock } from 'overmind'
import { config } from './'

describe('Actions', () => {
  describe('getPost', () => {
    test('should get post with passed id', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost(id) {
            return Promise.resolve({
              id
            })
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.state).toEqual({
        isLoadingPost: false,
        currentPost: { id: '1' },
        error: null
      })
    })
    test('should handle errors', async () => {
      const overmind = createOvermindMock(config, {
        api = {
          getPost() {
            throw new Error('test')
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.state.isLoadingPost).toBe(false)
      expect(overmind.state.error.message).toBe('test')
    })
  })
})
```

{% endtab %}
{% endtabs %}

If your actions can result in multiple scenarios a unit test is beneficial. But you will be surprised how straightforward the logic of your actions will become. Since effects are encouraged to be application specific you will most likely be testing those more than you will test any action.

You do not have to explicitly write the expected state. You can also use for example [JEST](https://www.overmindjs.org/guides/intermediate/05_writingtests?view=react\&typescript=true) for snapshot testing. The mock instance has a list of mutations performed. This is perfect for snapshot testing.

{% tabs %}
{% tab title="overmind/actions.test.js" %}

```typescript
import { createOvermindMock } from 'overmind'
import { config } from './'

describe('Actions', () => {
  describe('getPost', () => {
    test('should get post with passed id', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost(id) {
            return Promise.resolve({
              id
            })
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.mutations).toMatchSnapshot()
    })
    test('should handle errors', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost() {
            throw new Error('test')
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.mutations).toMatchSnapshot()
    })
  })
})
```

{% endtab %}
{% endtabs %}

In this scenario we would also ensure that the **isLoadingPost** state indeed flipped to *true* before moving to *false* at the end.

## Testing onInitialize

The **onInitialize** hook will not trigger during testing. To test this action you have to trigger it yourself.

{% tabs %}
{% tab title="overmind/onInitialize.test.js" %}

```typescript
import { createOvermindMock } from 'overmind'
import { config } from './'

describe('Actions', () => {
  describe('onInitialize', () => {
    test('should initialize with local storage theme', async () => {
      const overmind = createOvermindMock(config, {
        localStorage: {
          getTheme() {
            return 'awesome' 
          }
        }
      })

      await overmind.onInitialize()

      expect(overmind.state.theme).toEqual('awesome')
    })
  })
})
```

{% endtab %}
{% endtabs %}

### Testing effects <a href="#writing-tests-testing-effects" id="writing-tests-testing-effects"></a>

Where you want to put in your effort is with the effects. This is where you have your chance to build a domain specific API for your actual application logic. This is the bridge between some generic tool and what your application actually wants to use it for.

A simple example of this is doing requests. Maybe you want to use e.g. [AXIOS](https://github.com/axios/axios) to reach your API, but you do not really care about testing that library. What you want to test is that it is used correctly when you use your application specific API.

This is just an example showing you how you can structure your code for optimal testability. You might prefer a different approach or maybe rely on integration tests for this. No worries, you do what makes most sense for your application:

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
import * as axios from 'axios'

// This is the class we can create new instances of when testing
export class Api {
  constructor(request, options) {
    this.request = request
    this.options = options
  }
  async getPost(id: string) {
    try {
      const response = await this.request.get(this.options.baseUrl + '/posts/' + id, {
        headers: {
          'Auth-Token': this.options.authToken
        }
      })

      return response.data
    } catch (error) {
      throw new Error('Could not grab post with id ' + id)
    }
  }
}

// We export the default instance that we actually use with our
// application
export const api = new Api(axios, {
  authToken: '134981091031hfh31',
  baseUrl: '/api'
})
```

{% endtab %}
{% endtabs %}

Let’s see how you could write a test for it:

{% tabs %}
{% tab title="overmind/effects.test.js" %}

```typescript
import { Api } from './effects'

describe('Effects', () => {
  describe('Api', () => {
    test('should get a post using baseUrl and authToken in header', async () => {
      expect.assertions(3)
      const api = new Api({
        get(url, config) {
          expect(url).toBe('/test/posts/1')
          expect(config).toEqual({
            headers: {
              'Auth-Token': '123'
            }
          })

          return Promise.resolve({
            response: {
              id
            }
          })
        }
      }, {
        authToken: '123',
        baseUrl: '/test'
      })

      const post = await api.getPost('1')

      expect(post.id).toBe('1')
    })
  })
})
```

{% endtab %}
{% endtabs %}

Again, effects are where you typically have your most brittle logic. With the approach just explained you will have a good separation between your application logic and the brittle and “impure”. In an Overmind app, especially written in Typescript, you get very far just testing your effects and then do integration tests for your application. But as mentioned in the introduction we all have very different opinions on this, at least the API allows testing to whatever degree you see fit.


# action

```typescript
import { AsyncAction } from 'overmind'

export const getPosts: AsyncAction = async ({ state, actions, effects }) => {
  state.isLoadingPosts = true
  state.posts = await effects.api.getPosts()
  state.isLoadingPosts = false
}
```

An action is where you write the logic of the application. Every action receives at least one argument and that is the **context**. This is the signature of the context:

`{ state, actions, effects }`

This *injected* context allows Overmind to understand from where you are changing state and running effects. You can also use other actions defined in your application. Additionally with *injection* your actions become highly testable as it can easily be mocked.

State changes are restricted to these actions. That means if you try to change the state outside of an action you will get an error. The state changes are also scoped to the action. That means it does not matter if you perform the state change asynchronously, either by defining the action as an **async** function or for example use a **setTimeout**. You can change the state at any time within the action.

## Payload

When an action is called you can optionally pass it a payload. This payload is received as the second argument to the action.

```typescript
import { Action } from 'overmind'

export const setTitle: Action<string> = ({ state }, title) => {
  state.title = title
}
```

{% hint style="info" %}
There is only one argument, which means if you want to pass multiple values you have to do so with an object
{% endhint %}

## Typing

There are two different action types in Overmind, **Action** and **AsyncAction**. Both of them takes an Input param and an Output param where both of them default to **void**.

`Action<void, void>`

`AsyncAction<void, void>`.

The difference is that **AsyncAction** returns a Promise of the output, **Promise\<void>**. Basically whenever you use an **async** action or explicitly return a promise from an action you should use the **AsyncAction** type.


# addFlushListener

The **addMutationListener** triggers whenever there is a mutation. The **addFlushListener** triggers whenever Overmind tells components to render again. It can have multiple mutations related to it.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

const onInitialize: OnInitialize = async ({ state, effects }, overmind) => {
  overmind.addFlushListener(effects.history.addMutations)
}

export default onInitialize
```

{% endtab %}
{% endtabs %}


# addMutationListener

It is possible to listen to all mutations performed in Overmind. This allows you to create special effects based on mutations within a certain domain of your app, or whatever else you come up with. Note that this method triggers right after any mutation occurs, you might rather want to use **addFlushListener** to be notified about batched changes, like the components does.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

const onInitialize: OnInitialize = async ({ state, localStorage }, overmind) => {
  overmind.addMutationListener((mutation) => {
    if (mutation.path.indexOf('todos') === 0) {
      localStorage.set('todos', state.todos)
    }
  })
}

export default onInitialize
```

{% endtab %}
{% endtabs %}


# createOvermind

The **createOvermind** factory is used to create the application instance. You need to create and export a mechanism to connect your instance to the components. Please look at the guides for each view layer for more information.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { state } from './state'
import * as effects from './effects'
import * as actions from './actions'

export const config = {
  state,
  effects,
  actions
}

// For explicit typing check the Typescript guide
declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}

You can pass a second argument to the **createOvermind** factory. This is an options object with the following properties.

## options.devtools

If you develop your app on localhost the application connects to the devtools on **localhost:3031**. You can change this in case you need to use an IP address, the devtools is configured with a different port or you want to connect to localhost (with default port) even though the app is not on localhost.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/api/app_options_devtools.ts)

```typescript
const overmind = createOvermind(config, {
  devtools: true // 'localhost:3031'
})
```

## options.logProxies

By default, in **development**, Overmind will make sure that any usage of **console.log** will log out the actual object/array, instead of any proxy wrapping it. This is most likely what you want. If you want to turn off this behaviour, set this option to **true**.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/api/app_options_logproxies.ts)

```typescript
const overmind = createOvermind(config, {
  logProxies: false
})
```

## options.name

If you have multiple instances of Overmind on the same page you can name your app to differentiate them.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/api/app_options_name.ts)

```typescript
const overmindA = createOvermind(configA, {
  name: 'appA'
})

const overmindB = createOvermind(configB, {
  name: 'appB'
})
```

## options.hotReloading

By default Overmind will do the necessary hot reloading mechanism to keep your state, actions and effects updated. You might not want to use this feature or Overmind does not correctly detect that hot reloading should be turned off. You can turn it off with an option.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/api/app_options_hotreloading.ts)

```typescript
const overmind = createOvermind(config, {
  hotReloading: false
})
```

## options.delimiter

By default Overmind will create state paths using `.` as delimiter. This is used to give each state value an address and is used with the devtools. If any state keys uses `.` you will get weird behaviour in the devtools. You can now change this delimiter to a safe value, typically `' '` or `'|'` :

```typescript
const overmind = createOvermind(config, {
  delimiter: '.'
})
```

## options.devEnv

The default development environment in Overmind is called `development` , but you can change this to a custom name:

```typescript
const overmind = createOvermind(config, {
  devEnv: 'dev'
})
```


# createOvermindMock

The **createOvermindMock** factory creates an instance of Overmind which can be used to test actions. You can mock out effects and evaluate mutations performed during action execution.

{% tabs %}
{% tab title="overmind/actions.test.ts" %}

```typescript
import { createOvermindMock } from 'overmind'
import { config } from './'

describe('Actions', () => {
  describe('getPost', () => {
    test('should get post with passed id', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost(id) {
            return Promise.resolve({
              id
            })
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.mutations).toMatchSnapshot()
    })
    test('should handle errors', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost() {
            throw new Error('test')
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.mutations).toMatchSnapshot()
    })
  })
})
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
It is important that you separate your **config** from the instantiation of Overmind, meaning that **createOvermind** should not be used in the same file as the config you see imported here, it should rather be used where you render your application. This allows the config to be used for multiple purposes.
{% endhint %}


# createOvermindSSR

The **createOvermindSSR** factory creates an instance of Overmind which can be used on the server with server side rendering. It allows you to change state and extract the mutations performed, which can then be rehydrated on the client.

{% tabs %}
{% tab title="server/routePosts.ts" %}

```typescript
import { createOvermindSSR } from 'overmind'
import { config } from '../client/overmind'
import db from './db'

export default async (req, res) => {
  const overmind = createOvermindSSR(config)

  overmind.state.currentPage = 'posts'
  overmind.state.posts = await db.getPosts()

  const html = renderToString(
    // Whatever your view layer does to produce the HTML
  )

  res.send(`
<html>
  <body>
    <div id="app">${html}</div>
    <script>
      window.__OVERMIND_MUTATIONS = ${JSON.stringify(overmind.hydrate())}
    </script>
    <script src="/scripts/app.js"></script>
  </body>
</html>
`)
}
```

{% endtab %}
{% endtabs %}

## rehydrate

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize, rehydrate } from 'overmind'

export const onInitialize: OnInitialize = ({ state }) => {
  const mutations = window.__OVERMIND_MUTATIONS

  rehydrate(state, mutations)
}
```

{% endtab %}
{% endtabs %}


# derived

You can add derived state to your application. You access derived state like any other value, there is no need to call it as a function. The derived value is cached and will only update when any accessed state changes.

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { derived } from 'overmind'

export const state: State = {
  items: [],
  completedItems: derived((state, rootState) => {
    return state.items.filter(item => item.completed)
  })
}
```

{% endtab %}
{% endtabs %}

The function defining your derived state receives two arguments. The first argument is the object the derived function is attached to. Ideally you use this argument to produce the derived state, though you can access the second argument which is the root state of the application. The root state allows you to access any state.

{% hint style="info" %}
Accessing **rootState** might cause unnecessary updates to the derived function as it will track more state, though typically not an issue
{% endhint %}


# effects

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import { User, Item } from './state'

export const api = {
  async getUser(): Promise<User> {
    const response = await fetch('/user')

    return response.json()
  },
  async getItem(id: number): Promise<Item> {
    const response = await fetch(`/items/${id}`)

    return response.json()
  }
}
```

{% endtab %}
{% endtabs %}

Effects is really just about exposing existing libraries or create your own APIs for doing side effects. When these effects are attached to the application they will be tracked by the devtools giving you additional debugging information. By “injecting” the effects this way also open up for better testability of your logic.


# events

Overmind emits events during execution of actions and similar. It can be beneficial to listen to these events for analytics or maybe you want to create a custom debugging experience. The following events can be listened to by adding a listener to the eventHub:

```typescript
overmind.eventHub.on('action:start', (execution) => {})
overmind.eventHub.on('action:end', (execution) => {})
overmind.eventHub.on('operator:start', (execution) => {})
overmind.eventHub.on('operator:end', (execution) => {})
overmind.eventHub.on('operator:async', (execution) => {})
overmind.eventHub.on('mutations', (executionAndMutations) => {})
overmind.eventHub.on('derived', (derived) => {})
overmind.eventHub.on('derived:dirty', (derivedPathAndFlush) => {})

// Only during development
overmind.eventHub.on('effect', (effectDetails) => {})
overmind.eventHub.on('getter', (getterDetails) => {})
overmind.eventHub.on('component:add', (componentDetails) => {})
overmind.eventHub.on('component:update', (componentDetails) => {})
overmind.eventHub.on('component:remove', (componentDetails) => {})
```


# json

Overmind wraps objects and arrays in your state structure with proxies. If you pass state to 3rd party libraries, to a service worker or similar, you should pass a long a copy of that state. This avoids the 3rd party tool from mutating your state when you do not want it to.

```typescript
import { json } from 'overmind'

const copy = json(someValue)
```

This function does a copy of any plain object or array, which are the only values that is wrapped with proxies. This ensures minimal work is done and keeps all other values alone.


# lazy

You can lazy load configurations. You do this by giving each configuration a key with a function that returns the config when called. To actually load the configurations you can either call an effect or an action with the key of the configuration to load.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { lazy } from 'overmind/config'

export const config = lazy({
  moduleA: async () => await import('./moduleA').config
})
```

{% endtab %}

{% tab title="overmind/moduleA/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
export const loadModule = async ({ actions }) => {
  await actions.lazy.loadConfig('moduleA')
}
```

{% endtab %}
{% endtabs %}


# merge

Allows you to merge configurations together.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import {IConfig } from 'overmind'
import { merge } from 'overmind/config'
import * as moduleA from './moduleA'
import * as moduleB from './moduleB'

export const config = merge(moduleA, moduleB)

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}

Note that merge can be useful to combine a root configuration with **namespaced** or **lazy** configuration.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import {IConfig } from 'overmind'
import { merge, namespaced, lazy } from 'overmind/config'
import { state } from './state'
import * as moduleA from './moduleA'
import { Config as ModuleB } from './moduleB'

export const config = merge(
  {
    state
  },
  namespaced({
    moduleA
  }),
  lazy({
    moduleB: async (): Promise<ModuleB> => await import('./moduleB').config
  })
)

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}


# namespaced

Allows you to namespace configurations by a key.

The point of namespaces is to structure your code into domains, not isolate them. The reason being is that we more often than not design our namespaces wrong. We have no idea how the final app will look and getting into the issue of "cross domain logic and state" is a pain to refactor all the time due to wrong isolation.

So in Overmind isolation is a discipline, not a technical restriction.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import {IConfig } from 'overmind'
import { namespaced } from 'overmind/config'
import * as moduleA from './moduleA'
import * as moduleB from './moduleB'

export const config = namespaced({
  moduleA,
  moduleB
})

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}


# onInitialize

If you need to run logic as the application initializes you can use the **onInitialize** hook. This is defined as an action and it receives the application instance as the input value. You can do whatever you want here. Set initial state, run an action, configure a router etc.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

export const onInitialize: OnInitialize = async ({
  state,
  actions,
  effects
}, overmind) => {
  const initialData = await effects.api.getInitialData()
  state.initialData = initialData
}
```

{% endtab %}

{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { onInitialize } from './onInitialize'
import { state } from './state'
import * as actions from './actions'

export const config = {
  onInitialize,
  state,
  actions
}

// For explicit typing check the Typescript guide
declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}


# operators

Overmind also provides a functional API to help you manage complex logic. This API is inspired by asynchronous flow libraries like RxJS, though it is designed to manage application state and effects. If you want to create and use a traditional action “operator style” you define it like this:

```typescript
import { Operator, mutate } from 'overmind'

export const changeFoo: <T>() => Operator<T> = () =>
  mutate(({ state }) => {
    state.foo = 'bar'
  })
```

The **mutate** function is one of many operators. Operators are small composable pieces of logic that can be combined in many ways. This allows you to express complexity in a declarative way. You typically use the **pipe** operator in combination with the other operators to do this:

```typescript
import { Operator, pipe, debounce } from 'overmind'
import { QueryResult } from './state'
import * as o from './operators'

export const search: Operator<string> = pipe(
  o.setQuery(),
  o.filterValidQuery(),
  debounce(200),
  o.queryResult()
)
```

Any of these operators can be used with other operators. You can even insert a pipe inside an other pipe. This kind of composition is what makes functional programming so powerful.

## catchError

**async**

This operator runs if any of the previous operators throws an error. It allows you to manage that error by changing your state, run effects or even return a new value to the next operators.

```typescript
import { Operator, pipe, mutate, catchError } from 'overmind'

export const doSomething: Operator<string> = pipe(
  mutate(() => {
    throw new Error('foo')
  }),
  mutate(() => {
    // This one is skipped
  })
  catchError(({ state }, error) => {
    state.error = error.message

    return 'value_to_be_passed_on'
  }),
  mutate(() => {
    // This one continues executing with replaced value
  })
)
```

## debounce

When action is called multiple times within the set time limit, only the last action will move beyond the point of the debounce.

```typescript
import { Operator, pipe, debounce } from 'overmind'
import * as o from './operators'

export const search: Operator<string> = pipe(
  debounce(200),
  o.performSearch()
)
```

## filter

Stop execution if it returns false.

```typescript
import { Operator, filter } from 'overmind'

export const lengthGreaterThan: (length: number) => Operator<string> = (length) =>
  filter(function lengthGreaterThan(_, value) {
    return value.length > length
  })
```

## forEach

Allows you to pass each item of a value that is an array to the operator/pipe on the second argument.

```typescript
import { Operator, pipe, forEach } from 'overmind'
import { Post } from './state'
import * as o from './operators'

export const openPosts: Operator<string, Post[]> = pipe(
  o.getPosts(),
  forEach(o.getAuthor())
)
```

## fork

Allows you to execute an operator/pipe based on the matching key.

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { fork, Operator } from 'overmind'
import { User } from './state'

export const forkUserType: (paths: { [key: string]: Operator<User> }) => Operator<User> = (paths) =>
  fork(function forkUserType(_, user) {
    return user.type
  }, paths)
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe } from 'overmind'
import * as o from './operators'
import { UserType } from './state'

export const getUser: Operator<string, User> = pipe(
  o.getUser(),
  o.forkUserType({
    [UserType.ADMIN]: o.doThis(),
    [UserType.SUPERUSER]: o.doThat()
  })
)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
You have to use **ENUM** for these keys
{% endhint %}

## map

Returns a new value to the pipe. If the value is a promise it will wait until promise is resolved.

```typescript
import { Operator, map } from 'overmind'
import { User } from './state'

export const getEventTargetValue: () => Operator<Event, string> = () =>
  map(function getEventTargetValue(_, event) {
    return event.currentTarget.value
  })
```

## mutate

**async**

You use this operator whenever you want to change the state of the app. Any returned value is ignored.

```typescript
import { Operator, mutate } from 'overmind'

export const setUser: () => Operator<User> = () =>
  mutate(function setUser({ state }, user) {
    state.user = user
  })
```

## noop

This operator does absolutely nothing. Is useful when paths of execution is not supposed to do anything.

```typescript
import { Operator } from 'overmind'
import * as o from './operators'

export const doSomething: Operator = o.forkUserType({
  superuser: o.doThis(),
  admin: o.doThat(),
  other: o.noop()
})
```

## parallel

Will run every operator and wait for all of them to finish before moving on. Works like *Promise.all*.

```typescript
import { Operator, parallel } from 'overmind'
import * as o from './operators'

export const loadAllData: Operator = parallel(
  o.loadSomeData(),
  o.loadSomeMoreData()
)
```

## pipe

The pipe is an operator in itself. Use it to compose other operators and pipes.

```typescript
import { Operator, pipe } from 'overmind'
import { Item } from './state'
import * as o from './operators'

export const openItem: Operator<string, Item> = pipe(
  o.openItemsWhichIsAPipeOperator(),
  o.getItem()
)
```

## run

This operator allows you to run side effects. You can not change state and you can not return a value.

```typescript
import { Operator, run } from 'overmind'

export const doSomething: <T>() => Operator<T> = () =>
  run(function doSomething({ effects }) {
    effects.someApi.doSomething()
  })
```

## throttle

This operator allows you to ensure that if an action is called, the next action will only continue past this point if a certain duration has passed. Typically used when an action is called many times in a short amount of time.

```typescript
import { Operator, pipe, throttle } from 'overmind'
import * as o from './operators'

export const onMouseDrag: Operator<string> = pipe(
  throttle(200),
  o.handleMouseDrag()
)
```

## tryCatch

This operator allows you to scope execution and manage errors. This operator does not return a new value to the execution.

```typescript
import { Operator, pipe, tryCatch } from 'overmind'
import * as o from './operators'

export const doSomething: Operator<string> = tryCatch({
  try: o.somethingThatMightError(),
  catch: o.somethingToHandleTheError()
})
```

## wait

Hold execution for set time.

```typescript
import { Operator, pipe, wait } from 'overmind'
import * as o from './operators'

export const search: Operator<string> = pipe(
  wait(2000),
  o.executeSomething()
)
```

## waitUntil

Wait until a state condition is true.

```typescript
import { Operator, pipe, waitUntil } from 'overmind'
import * as o from './operators'

export const search: Operator<string> = pipe(
  waitUntil(state => state.count === 3),
  o.executeSomething()
)
```

## when

Go down the true or false path based on the returned value.

```typescript
import { Operator, when } from 'overmind'
import { User } from './state'

export const whenUserIsAwesome: (paths: { true: Operator<User>, false: Operator<User> }) => Operator<User> = (paths) => 
  when(function whenUserIsAwesome(_, user) {
    return user.isAwesome
  }, paths)
```


# reaction

Sometimes you need to react to changes to state. Typically you want to run some imperative logic related to something in the state changing.

```typescript
reaction(
  // Access and return some state to react to
  (state) => state.foo,

  // Do something with the returned value
  (foo) => {},

  {
    // If you return an object or array from the state you can set this to true.
    // The reaction will run when any nested changes occur as well
    nested: false,

    // Runs the reaction immediately
    immediate: false
  }
)
```

There are two points of setting up reactions in Overmind.

## onInitialize

The onInitialize hook is where you set up reactions that lives throughout your application lifetime. The reaction function returns a function to dispose it. That means you can give effects the possibility to create and dispose of reactions in any action.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

export const onInitialize: OnInitialize = ({ effects }, instance) => {
  instance.reaction(
    ({ todos }) => todos,
    (todos) => effects.storage.saveTodos(todos),
    {
      nested: true
    }
  )
}
```

{% endtab %}
{% endtabs %}

## components

With components you typically use reactions to manipulate DOM elements or other UI related imperative libraries.

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const App: React.FC = () => {
  const { reaction } = useOvermind()

  React.useEffect(() => reaction(
    ({ currentPage }) => currentPage,
    () => {
      document.querySelector('#page').scrollTop = 0
    }
  ))

  return <div id="page"></div>
}

export default App
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
  <div id="page"></div>
  `
})
export class App {
  constructor(private store: Store) {}
  ngOnInit() {
    this.store.reaction(
      ({ currentPage }) => currentPage,
      () => {
        document.querySelector('#page').scrollTop = 0
      }    
    )
  }
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <div id="page"></div>
</template>
<script>
export default {
  mounted() {
    this.overmind.reaction(
      ({ currentPage }) => currentPage,
      () => {
        document.querySelector('#page').scrollTop = 0
      }     
    )
  }
}
</script>
```

{% endtab %}
{% endtabs %}


# rehydrate

It is possible to update the complete state of Overmind using the **rehydrate** tool. It allows you to update the state either with a state object or an array of mutations, typically collected from server side rendering.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { rehydrate } from 'overmind'

export const onInitialize = ({ state, effects }) => {
  // Grab mutations from a server rendered version
  const mutations = window.__OVERMIND_MUTATIONS

  rehydrate(state, mutations)

  // Grab a previous copy of the state, for example stored in
  // localstorage
  rehydrate(state, effects.storage.get('previousState') || {})
}
```

{% endtab %}
{% endtabs %}

The function takes into acount the state structure of Overmind which is based on objects where functions are derived state. That means it will leave derived state alone, resulting in them rather updating if any of their dependecies where updated by rehydration.


# statemachine

A statematchine allows you to wrap state with transitions. That means you can protect your logic from running in invalid states of the application.

## Create a statemachine

You define a whole namespace as a statemachine, you can have a nested statemachine or you can even put statemachines inside statemachines.

```javascript
import { statemachine } from 'overmind'

export const state = statemachine({
  UNAUTHENTICATED: ['AUTHENTICATING'],
  AUTHENTICATING: ['UNAUTHENTICATED', 'AUTHENTICATED'],
  AUTHENTICATED: ['UNAUTHENTICATED']
}, {
  state: 'UNAUTHENTICATED'
})
```

Instead of only defining state, you first define a set of transitions. The key represents a transition state, here **UNAUTHENTICATED**, **AUTHENTICATING** and **AUTHENTICATED**. Then we define an array which shows the next transition state can occur in the given transition state. When **UNAUTHENTICATED** we can move into the **AUTHENTICATING** state for example. When in **AUTHENTICATING** state we can move either back to **UNAUTHENTICATED** due to an error or we might move to **AUTHENTICATED**. The point is... when you are **UNAUTHENTICATED**, you can not run logic related to being **AUTHENTICATED**. And when **AUTHENTICATING** you can not run that logic again until you are back in **UNAUTHENTICATED**.

As actual state values we define the initial transition state of **UNAUTHENTICATED**.

If we wanted we could extend the state with other values, as normal.

```javascript
import { statemachine } from 'overmind'

export const state = statemachine({
  UNAUTHENTICATED: ['AUTHENTICATED'],
  AUTHENTICATING: ['UNAUTHENTICATED', 'AUTHENTICATED'],
  AUTHENTICATED: ['UNAUTHENTICATED']
}, {
  state: 'UNAUTHENTICATED',
  todos: {},
  filter: 'all'
})
```

## Transition between states

The transition states are also part of the resulting **state** object, in this case:

```javascript
// The resulting state object
export const state = {
  UNAUTHENTICATED: () => {...},
  AUTHENTICATING: () => {...},
  AUTHENTICATED: () => {...},
  state: 'UNAUTHENTICATED',
  todos: {},
  filter: 'all'
}
```

That means you can call **UNAUTHENTICATED**, **AUTHENTICATING** and **AUTHENTICATED** as functions to transition into the new states. And this is an example of how you would use them:

```javascript
export const login = ({ state, effects }) => {
  return state.AUTHENTICATING(() => {
    try {
      const user = await effects.api.login()
      return state.AUTHENTICATED(() => {
        state.user = user
      })
    } catch (error) {
      return state.UNAUTHENTICATED(() => {
        state.error = error
      })
    }
  })
}
```

When a component, or something else, calls the **login** action it will first try to move into the **AUTHENTICATING** state. If this is not possible, nothing else will happen. Then we go ahead an login, which returns a user. If we were to try to set the user immediately an error would be thrown, because it is being set "out of scope of the transition" (asynchronously). To actually set the user we first transition to **AUTHENTICATED** and given that is a valid transition the user will be set.

What we accomplish in practice here is to ensure that changes to state is guarded by these transitions, which results in more predictable and safer code.


# Overmind

frictionless state management

> Web application development is about **defining**, **changing** and **consuming state** to produce a user experience. Overmind aims for a developer experience where that is all you focus on, reducing the orchestration of state management to a minimum. Making you a **happier** and more **productive** developer!

{% embed url="<https://overmindjs.changefeed.app/general/v23>" %}

## APPLICATION INSIGHT

Develop the application state, effects and actions without leaving [VS Code](https://code.visualstudio.com/), or use the standalone development tool. Everything that happens in your app is tracked and you can seamlessly code and run logic to verify that everything works as expected without necessarily having to implement UI.

![](/files/-Ly_HBec6C-YihjahYdA)

## A SINGLE STATE TREE

Building your application with a single state tree is the most straight forward mental model. You get a complete overview, but can still organize the state by namespacing it into domains. The devtools allows you to edit and mock out state.

```typescript
{
  isAuthenticating: false,
  dashboard: {
    issues: [],
    selectedIssueId: null,
  },
  user: null,
  form: new Form()
}
```

## SEPARATION OF LOGIC

Separate 3rd party APIs and logic not specific to your application by using **effects**. This will keep your application logic pure and without low level APIs cluttering your code.

{% tabs %}
{% tab title="api.js" %}

```javascript
export const fetchItems = async () {
    const response = await fetch('/api/items')

    return response.json()
  }
}
```

{% endtab %}

{% tab title="actions.js" %}

```typescript
export const loadApp = ({ state, effects }) => {
  state.items = await effects.api.fetchItems()
}
```

{% endtab %}
{% endtabs %}

## SAFE AND PREDICTABLE CHANGES

When you build applications that perform many state changes things can get out of hand. In Overmind you can only perform state changes from **actions** and all changes are tracked by the development tool.

```javascript
export const getItems = async ({ state, effects }) => {
  state.isLoadingItems = true
  state.items = await effects.api.fetchItems()
  state.isLoadingItems = false
}
```

## COMPLEXITY TOOLS

Even though Overmind can create applications with only plain **state** and **actions**, you can use **opt-in** tools like **functional operators**, **statecharts, statemachines** and state values defined as a **class,** to manage complexities of your application.

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

```javascript
export const search = pipe(
  mutate(({ state }, query) => {
    state.query = query
  }),
  filter((_, query) => query.length > 2),
  debounce(200),
  mutate(async ({ state, effects }, query) => {
    state.isSearching = true
    state.searchResult = await effects.getSearchResult(query)
    state.isSearching = false
  })
)
```

{% endtab %}

{% tab title="Statechart" %}

```javascript
const loginChart = {
  initial: 'LOGIN',
  states: {
    LOGIN: {
      on: {
        changeUsername: null,
        changePassword: null,
        login: 'AUTHENTICATING'
      }
    },
    AUTHENTICATING: {
      on: {
        resolveUser: 'AUTHENTICATED',
        rejectUser: 'ERROR'
      }
    },
    AUTHENTICATED: {
      on: {
        logout: 'LOGIN'
      }
    },
    ERROR: {
      on: {
        tryAgain: 'LOGIN'
      }
    }
  }
}
```

{% endtab %}

{% tab title="Statemachines" %}

```typescript
export const state = {
  mode: statemachine({
    initial: 'unauthenticated',
    states: {
      unauthenticated: ['authenticating'],
      authenticating: ['unauthenticated', 'authenticated'],
      authenticated: ['unauthenticating'],
      unauthenticating: ['unauthenticated', 'authenticated']
    }
  }),
  user: null,
  error: null
}
```

{% endtab %}

{% tab title="Class state" %}

```javascript
class LoginForm() {
  private username = ''
  private password = ''
  private validationError = ''
  changeUsername(username) {
    this.username = username
  }
  changePassword(password) {
    if (!password.match([0-9]) {
      this.validationError = 'You need some numbers in your password'
    }
    this.password = password
  }
  isValid() {
    return Boolean(this.username && this.password) 
  }
}

export const state = {
  loginForm: new LoginForm()
}
```

{% endtab %}
{% endtabs %}

## SNAPSHOT TESTING OF LOGIC

Bring in your application configuration of state, effects and actions. Create mocks for any effects. Take a snapshot of mutations performed in an action to ensure all intermediate states are met.

```javascript
import { createOvermindMock } from 'overmind'
import { config } from './'

test('should get items', async () => {
  const overmind = createOvermindMock(config, {
    api: {
      fetchItems: () => Promise.resolve([{ id: 0, title: "foo" }])
    }
  })

  await overmind.actions.getItems()

  expect(overmind.mutations).toMatchSnapshot()
})
```

## WE WROTE THE TYPING

Overmind has you covered on typing. If you choose to use Typescript the whole API is built for excellent typing support. You will not spend time telling Typescript how your app works, Typescript will tell you!

## RUNNING CODESANDBOX

![](/files/-LyeprUbhOErEqwCnRkJ)

Overmind is running the main application of [codesandbox.io](https://codesandbox.io). Codesandbox, with its state and effects complexity, benefits greatly combining Overmind and Typescript.


# Introduction

In this introduction you will get an overview of Overmind and how you can think about application development. We will be using [REACT](https://reactjs.org/) to write the UI, but you can use Overmind with [VUE](https://vuejs.org/) and [ANGULAR](https://angular.io/) if either of those is your preference.

{% hint style="info" %}
If you rather want to go right ahead and set up a local project, please have a look at the [QUICKSTART](/v23/quickstart) guide.
{% endhint %}

Before we move on, have a quick look at this sandbox. It is a simple counter application and it gives you some foundation before talking more about Overmind and building applications.

{% embed url="<https://codesandbox.io/s/overmind-counter-c4tuh?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

## Application state VS Component state

First of all we have to talk about **application** and **component** state. In the counter example above we chose to define our **count** state as application state, outside of the component. We could have defined the count inside the component instead and the application would work exactly the same. So why did we choose application state?

If the count example above was the entire application it would not make any sense to introduce application state and Overmind. But if you were to increase the scope of this simple application you would be surprised how quickly you get into the following scenarios:

1. **You want to introduce an other component that needs to know about the current state of the count.** This new component can not be a parent of the component owning the count state. It can not be a sibling either. It has to be a child. If it is not an immediate child the count state has to be passed down the component tree until it reaches your new component.
2. **You want to remember the count, even though it is not shown in the UI**. Your count is behind one of multiple tabs in the UI. When the user changes the tabs you do not want the count to reset. The only way to ensure this is to move the count state up to a parent component that is no longer a child of the tab and then pass the count state back down again.
3. **You want to change the count from a side effect**. You have a websocket connection which changes the count when a message is received. If you want to avoid this websocket connection to open and close as the component mounts and unmounts you will have to move the websocket connection up the component tree.
4. **You want to change the count as part of multiple changes**. When you click the increase count button you need to change both the count state and an other state related to a different part of the UI. To be able to change both states at the same time, they have to live inside the same component, which has to be a parent of both components using the state.

Introducing these scenarios we said: **You want**. In reality we rarely know exactly what we want. We do not know how our state and components will evolve. And this is the most important point. By using application state instead of component state you get flexibility to manage whatever comes down the road without having to refactor wrong assumptions.

**So is component state bad?** No, certainly not. You do not want to overload your application state with state that could just as well have been inside a component. The tricky thing is to figure out when that is absolutely the case. For example:

1. **Modals should certainly be component state?** Not all modals are triggered by a user interaction. A profile modal might be triggered by clicking a profile picture, but also open up when a user opens the application and is missing information.
2. **The active tab should certainly be component state?** The active tab might be part of the url query, `/user?tab=count`. That means it should rather be a hyperlink where your application handles the routing and provides state to identify the active tab.
3. **Inputs should certainly be component state?** If the input is part of an application flow, you might want to empty out the content of that input related to other changes, or even change it to something else.

How you want to go about this is totally up to you. We are not telling you exactly how to separate application and component state. What we can tell you though; **“If you lean towards application state your are more flexible to future changes”**.

## Defining state

As you can see in the count example we added a state object when we created the instance.

```javascript
createOvermind({
  state: {
    count: 0
  },
  ...
})
```

This state object will hold all the application state, we call it a *single state tree*. That does not mean you define all the state in one file and we will talk more about that later. For now let us talk about what you put into this state tree.

A single state tree typically favours serializable state. That means state that can be `JSON.parse` and `JSON.stringify` back and forth. It can be safely passed between the client and the server, localStorage or to web workers. You will use **strings**, **numbers**, **booleans**, **arrays**, **objects** and **null**. Overmind also has the ability to allow you define state values as class instances, even serializing back and forth. You can read more about that in [State](/v23/core/defining-state).

## Defining actions

When you need to change your state you define actions. Overmind only allows changing the state of the application inside the actions. An error will be thrown if you try to change the state inside a component. The actions are plain functions/methods. The only thing that makes them special is that they all receive a preset first argument, called **the context**:

```javascript
createOvermind({
  state: {
    count: 0
  },
  actions: {
    increaseCount({ state }) {
      state.count++;
    },
    decreaseCount({ state }) {
      state.count--;
    }
  }
})
```

Here we can see that we [DESTRUCTURE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) the context to grab the **state**. You can also access other actions on the context:

```javascript
createOvermind({
  state: {
    count: 0
  },
  actions: {
    increaseCount({ state, actions }) {
      state.count++;
      actions.decreaseCount()
    },
    decreaseCount({ state }) {
      state.count--;
    }
  }
})
```

And as we will see later you will also be using **effects** from the context.

## Increasing complexity

Now we will move to a more complex example. Please have a look:

{% embed url="<https://codesandbox.io/s/overmind-todomvc-simple-097zs?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

We have now separated out the Overmind related logic into its own file, **app.js**. This file creates the Overmind instance and also exports how the components will interact with the state and the actions, the hook called **useApp**. Vue and Angular has other mechanisms conventional to those frameworks where application state and actions can be accessed.

## References

What to take notice of is how we store the **todos** of this application.

```javascript
createOvermind({
  state: {
    ...
    todos: {},
    ...
  },
  ...
})
```

It is just an empty object. You might intuitively think of a list of todos as an array. Not blaming you, it makes total sense. That said, when you work with entities that has a unique identifier, typically an *id* property, you are better off storing them in an object. Each key in this object will be the unique identifier of a todo. For example:

```javascript
{
  'todo-1': {
    id: 'todo-1',
    title: 'My Todo',
    completed: false
  },
  'todo-2': {
    id: 'todo-2',
    title: 'My Other Todo',
    completed: true
  },
}
```

When you need to reference a todo, for example a component wants to reference a todo to toggle its completed state or maybe delete one, you will pass “todo-1” or “todo-2” as a reference instead of the todo itself.

Working with references this way avoids logic where you need to **find** a todo in an array or **filter**/**splice** out a todo to delete it from an array. You simply just point to the todos state to grab or delete it:

```javascript
state.todos[myReference]

delete state.todos[myReference]
```

Using references also ensures that only one instance of any todo will live in your state tree. The todo itself lives on the **todos** state, while everything else in the state tree references a todo by using its id. For example our **editingTodoId** state uses the id of a todo to reference which todo is currently being edited.&#x20;

## Deriving state

Looking through the example you have probably noticed these:

```javascript
createOvermind({
  state: {
    ...,
    currentTodos: ({ todos, filter }) => {
      return Object.values(todos).filter(todo => {
        switch (filter) {
          case 'active':
            return !todo.completed;
          case 'completed':
            return todo.completed;
          default:
            return true;
        }
      });
    },
    activeTodoCount: ({ todos }) => {
      return Object.values(todos).filter(todo => !todo.completed).length;
    },
    hasCompletedTodos: ({ todos }) => {
      return Object.values(todos).some(todo => todo.completed);
    },
    isAllTodosChecked: ({ currentTodos }) => {
      return currentTodos.every(todo => todo.completed);
    },
  },
  ...
})
```

Our state tree is concerned with state values that you will change using actions. But you can also automatically produce state values based on existing state. An example of this would be to list the **currentTodos**. It uses the todos and filter state to figure out what todos to actually display. Sometimes this is called computed state. We call it **derived** state.

Any function you insert into the state tree is treated as derived state. That means these functions receives a preset first argument which is the immediate state, the state object the derived is attached to. In bigger applications you might also need to use the second argument, which is the root state of the application. The derived will automatically track whatever state you use and then flag itself as dirty whenever it changes. If derived state is used while being dirty, the function will run again. If it is not dirty a cached value is returned.

## Effects

Now let us move into an even more complex application. Here we have added **effects**. Specifically effects to handle routing, storing todos to local storage and producing unique ids for the todos. We have added an **onInitialize** hook which is a special function Overmind runs when the application starts.

{% embed url="<https://codesandbox.io/s/overmind-todomvc-2im6p?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

You can think of effects as a contract between your application and the outside world. You write an effect API of **what** your application needs and some 3rd party tool or native JavaScript API will implement **how** to provide it. Let us look at the router:

```javascript
createOvermind({
  ...,
  effects: {
    ...,
    router: {
      initialize(routes) {
        Object.keys(routes).forEach(url => {
          page(url, ({ params }) => routes[url](params));
        });
        page.start();
      },
      goTo(url) {
        page.show(url);
      },
    },
  }
})
```

The router uses the [PAGE](https://www.npmjs.com/package/page) tool to manage routing. It takes a “url to action” option that makes sense for this application, but you could define this however you wanted.

```javascript
effects.router.initialize({
  '/': () => actions.changeFilter('all'),
  '/active': () => actions.changeFilter('active'),
  '/completed': () => actions.changeFilter('completed'),
});
```

This argument passed is transformed into something Page can understand. What this means is that we can easily switch out Page with some other tool later if we wanted to, or maybe if the app ran in different environments you could change out the implementation of the router dynamically. We were also able to combine **page** and **page.start** behind one method, which cleans up our application code. We did the same for the **storage** effect. We use localStorage and JSON.parse/JSON.stringify behind a single method.

## Scaling up the application

Defining all the state, actions and effects on one object would not work very well for a large application. A convention in Overmind is to split these concepts into different files behind folders representing a domain of the application. In this next sandbox you can see how we split up state, actions and effects into different files. They are all exposed through a main file representing that domain, in this case “the root domain”:

{% embed url="<https://codesandbox.io/s/overmind-todomvc-split-xdh41?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

Also notice that we have split up the instantiation of Overmind from the definition of the application. What this allows us to do is reuse the same application configuration for testing purposes and/or server side rendering. We separate the definition from the instantiation.

To scale up your code even more you can split it into **namespaces**. You can read more about that in the [STRUCTURING THE APP](/v23/core/structuring-the-app) guide.

## Get to know Typescript

Now that we have insight into the building blocks of Overmind it is time to introduce typing. If you are already familiar with [TYPESCRIPT](https://www.typescriptlang.org/) you will certainly enjoy the minimal typing required to get full type safety across your application. If you are unfamiliar with Typescript Overmind is a great project to start using it, for the very same reason.

Have a look at this new project where we have typed the application:

{% hint style="info" %}
You have to **OPEN IN EDITOR** to get the full Typescript experience.
{% endhint %}

{% embed url="<https://codesandbox.io/s/overmind-todomvc-typescript-39h7y?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

As you can see we only have to add an **Action** type to our functions and optionally give it an input type. This is enough for the action to give you all information about the application. Try changing some code and even add some code to see how Typescript helps you to explore the application and ensure that you implement new functionality correctly.

If you go to the **state.ts** file and change the type:

```typescript
export type State = {
  ...,
  newTodoTitle: string
  ...
}
```

to:

```typescript
export type State = {
  ...,
  todoTitle: string
  ...
}
```

You can now visit the **actions.ts** file and the **AddTodo.tsx** component. As you can see Typescript yells because the typing is now wrong. This is very powerful in complex projects which moves fast. The reason being that you can safely rename and refactor without worrying about breaking the code.

To learn more about Overmind and Typescript read the [TYPESCRIPT](https://www.overmindjs.org/guides/beginner/05_typescript) documentation.

## Development tool

Overmind also ships with its own development tool. It can be installed as a [VSCODE PLUGIN](https://marketplace.visualstudio.com/items?itemName=christianalfoni.overmind-devtools-vscode) or installed as an NPM package. The development tool knows everything about what is happening inside the application. It shows you all the state, running actions and connected components. By default Overmind connects automatically to the devtool if it is running. Try now by going to the **index.tsx** file and change:

```typescript
export const overmind = createOvermind(config, {
  devtools: false,
});
```

to:

```typescript
export const overmind = createOvermind(config, {
  devtools: true,
});
```

Go to your terminal and use the NPM executor to instantly fire up the development tool.

```
npx overmind-devtools@latest
```

Refresh the sandbox preview and you should see the devtools populated with information from the application.

{% hint style="info" %}
This only works in **CHROME** when running on codesandbox.io, due to domain security restrictions. It works on all browsers when running your project locally.
{% endhint %}

![](/files/-Ly_Ye8-PCJwaz9lUhuJ)

Here we get an overview of the current state of the application, including our derived state. If we move to the next tab we get an overview of the execution. We have not triggered any actions yet, but our **onInitialized** hook has run and triggered some logic.

![](/files/-Ly_YjTVWjycuO_dIxXo)

Here we can see that we grabbing todos from local storage and initializing our router. We can also see that the router instantly fires off our **changeFilter** action causing a state change on the filter. At the end we can see that our reaction triggered, saving the todos.

{% hint style="info" %}
You might wonder why the reaction triggered when it was defined after we changed the **todos** state. Overmind batches up changes to state and *flushes* at optimal points in the execution. For example when an action ends or some asynchronous code starts running. The reaction reacts to these flushes, just like components do.
{% endhint %}

Moving on we also get insight into components looking at our application state:

![](/files/-Ly_Yxpz7Z9HxOvpv-nB)

Currently two components are active in the application and we can also see what state they are looking at.

A chronological list of all state changes and effects run is available on the next tab. This can be useful with asynchronous code where actions changes state “in between” each other.

![](/files/-Ly_Z1fI66LDL5MCNQkc)

Now, let us try to add a new todo and see what happens.

![](/files/-Ly_Z7j6WSVu9swkIksn)

Our todo has been added and we can even see how the derived state was affected by this change. Looking at our actions tab we can see what state changes were performed and by hovering the mouse on the yellow label up right you get information about what components and derived were affected by state changes in this action.

![](/files/-Ly_ZE0yRYU9_L71s3WK)

## Managing complexity

Overmind gives you a basic foundation with its **state**, **actions** and **effects**. As mentioned previously you can split these up into multiple namespaces to organize your code. This manages the complexity of scaling. There is also a complexity of reusability and managing execution over time. The **operators** API allows you to split your logic into many different composable parts. With operators like **debounce**, **waitUntil** etc. you are able to manage execution over time. With the latest addition of **statecharts** you have the possiblity to manage the complexity of state and interaction. What interactions should be allowed in what states. And with state values as **class instances** you are able to co-locate state with logic.

The great thing about Overmind is that none of these concepts are forced upon you. If you want to build your entire app in the root namespace, only using actions, that is perfectly fine. You want to bring in operators for a single action to manage time complexity, do that. Or do you have a concept where you want to safely control what actions can run in certain states, use a statechart. Overmind just gives you tools, it is up to you to determine if they are needed or not.

## Moving from here

We hope this introduction got you excited about developing applications and working with Overmind. From this point you can continue working with [CODESANDBOX.IO](https://codesandbox.io/) or set up a local development flow. It is highly encouraged to use Overmind with Typescript, it does not get any more complex than what you see in this simple TodoMvc application.

Move over to the [QUICKSTART](/v23/quickstart) to get help setting up your project. The other guides will give you a deeper understanding of how Overmind works. If you are lost please talk to us on [DISCORD](https://discord.gg/YKw9Kd) and we are happy to help. And yeah… have fun! :-)


# Quickstart

From the command line install the Overmind package:

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

```
npm install overmind overmind-react
```

{% endtab %}

{% tab title="Vue" %}

```
npm install overmind overmind-vue
```

{% endtab %}

{% tab title="Angular" %}

```
npm install overmind overmind-angular
```

{% endtab %}
{% endtabs %}

### Setup

Now set up a simple application like this:

{% tabs %}
{% tab title="overmind/state.js" %}

```javascript
export const state = {
  title: 'My App'
}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

And fire up your application in the browser or whatever environment your user interface is to be consumed in by the users.

Move on with the specific view layer of choice to connect your app:

[**REACT** ](/v23/views/react)**-** [**ANGULAR**](/v23/views/angular) **-** [**VUE**](/v23/views/vue)


# How to learn

To learn any new tool it is important to have some goal unrelated to the tool itself. Maybe you have a pet project or a project at work you want to try it on. There is a lot on the menu on the left here, so let us give you some pointers to the most important docs to understand Overmind.

* [**The introduction video**](https://youtu.be/82Aq_ujnBQw) gives you a quick overview of what Overmind is
* You will benefit from getting into the overall structure with [**Configuration**](/v23/core/structuring-the-app)**,** then moving on to the specific concepts of [**State**](/v23/core/defining-state)**,** [**Actions**](/v23/core/writing-application-logic) and [**Effects**](/v23/core/running-side-effects)
* If you use Typescript it can be a good idea to already now explore how you use Overmind with [**Typescript**](/v23/core/typescript)
* Ready to start building something? Check of the view packages for [**React**](/v23/views/react), [**Angular**](/v23/views/angular) or [**Vue**](/v23/views/vue), to get you started
* Once you got a feel for it, the **Connecting components** guide will give you some more insight into how you use your state in the components
* From here it is totally up to you! Good luck and please visit our Discord channel for support


# Videos

## Overmind introduction

{% embed url="<https://youtu.be/82Aq_ujnBQw>" %}

## Devtools introduction

{% embed url="<https://youtu.be/j_dzXucq3E4>" %}

## Replacing Vuex with Overmind

{% embed url="<https://youtu.be/O5FMIXwYLAA>" %}

## VSCode extension

{% embed url="<https://youtu.be/P4CwiC0f56Y>" %}


# FAQ

## The devtool is not responding?

First… try to refresh your app to reconnect. If this does not work make sure that the entry point in your application is actually creating an instance of Overmind. The code **createOvermind(config)** has to run to instantiate the devtools.

## The devtools does not open in VS Code?

Restart VS Code

## My operator actions are not running?

Operators are identified with a Symbol. If you happen to use Overmind across packages you might be running two versions of Overmind. The same goes for core package and view package installed out of version sync. Make sure you are only running on package of Overmind by looking into your **node\_modules** folder.


# Devtools

## VS Code

For the best experience you should install the [OVERMIND DEVTOOLS](https://marketplace.visualstudio.com/items?itemName=christianalfoni.overmind-devtools-vscode) extension. This will allow you to work on your application without leaving the IDE at all.

![](/files/-Ly_HBec6C-YihjahYdA)

{% hint style="info" %}
If you are using the **Insiders** version of VSCode the extension will not work. It seems to be some extra security setting.
{% endhint %}

## Standalone app

Alternatively you can install the standalone application of the devtools. You can start it with the NPM executor as:

```javascript
npx overmind-devtools@latest
```

{% hint style="info" %}
Adding **@latest** just ensures that you break any caching, meaning you will always run the latest version
{% endhint %}

You can also install the devtools with your project, allowing you to lock a specific version of the devtools to your project:

```javascript
npm install overmind-devtools
```

With the package [CONCURRENTLY](https://www.npmjs.com/package/concurrently) you can start the devtools as you start your build process:

```
npm install overmind-devtools concurrently
```

{% code title="package.json" %}

```javascript
{
  ...
  "scripts": {
    "start": "concurrently \"overmind-devtools\" \"someBuildTool\""
  },
  ...
}
```

{% endcode %}

## Connecting from the application

When you create your application it will automatically connect through **localhost:3031**, meaning that everything should just work out of the box. If you need to change the port, connect the application over a network (mobile development) or similar, you can configure how the application connects:

```javascript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config, {
  devtools: '10.0.0.1:3031'
})
```

### Connecting on Chromebook

ChromeOS does not expose localhost as normal. That means you need to connect with **penguin.termina.linux.test:3031**, or you can use the following plugin to forward **localhost:**

{% embed url="<https://chrome.google.com/webstore/detail/connection-forwarder/ahaijnonphgkgnkbklchdhclailflinn/related?hl=en-US>" %}

## Hot Module Replacement

A popular concept introduced by Webpack is [HMR](https://webpack.js.org/concepts/hot-module-replacement/). It allows you to make changes to your code without having to refresh. Overmind automatically supports HMR. That means when **HMR** is activated Overmind will make sure it updates and manages its state, actions and effects. Even the devtools will be updated as you make changes.

Typically you add this, here showing with React:

```typescript
import React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import { App } from './components/App'


function start() {
  const overmind = createOvermind(config)

  render(<Provider value={overmind}><App /></Provider>, document.querySelector('#app'))
}

start()

if (module.hot) {
  module.hot.accept(() => {
    start()
  })
}
```

Though you can also manually only update Overmind by:

{% tabs %}
{% tab title="index.js" %}

```typescript
import React from 'react'
import { render } from 'react-dom'
import { overmind } from './overmindInstance'
import { Provider } from 'overmind-react'
import { App } from './components/App'

render(<Provider value={overmind}><App /></Provider>, document.querySelector('#app'))


```

{% endtab %}

{% tab title="overmindInstance.js" %}

```javascript
import { createOvermind } from 'overmind'
import { config } from './overmind'

export const overmind = createOvermind(config)

if (module.hot) {
  module.hot.accept('./overmind', () => {
    overmind.reconfigure(config)
  })
}
```

{% endtab %}
{% endtabs %}


# Configuration

Overmind is based on a core concept of:

`{ state, actions, effects }`

This data structure is called **the configuration** of your application. If it is a simple application you might have a single configuration, but typically you will create multiple of them and use tools to merge them together into one big configuration. But before we look at the scalability of Overmind, let’s talk about file structure.

## Domains

As your application grows you start to separate it into different domains. A domain might be closely related to a page in your application, or maybe it is strictly related to managing some piece of data. It does not matter. You define the domains of your application and they probably change over time as well. What matters in the context of Overmind though is that each of these domains will contain their own state, actions and effects. So imagine a file structure of:

```
overmind/
  state.ts
  actions.ts
  effects.ts
  index.ts
```

In this structure we are splitting up the different components of the configuration. This is a good first step. The **index** file acts as the file that brings the **state**, **actions** and **effects** together.

But if we want to split up into actual domains it would look more like this:

```
overmind/
  posts/
    state.ts
    actions.ts
    effects.ts
    index.ts
  admin/
    state.ts
    actions.ts
    effects.ts
    index.ts
  index.ts
```

In this case each domain **index** file bring its own state, actions and effects together and the **overmind/index** file is responsible for bringing the whole configuration together.

## The state file

You will typically define your **state** file by exporting a single constant named *state*.

{% tabs %}
{% tab title="overmind/posts/state.js" %}

```typescript
export const state = {
  posts: []
}
```

{% endtab %}

{% tab title="overmind/admin/state.js" %}

```typescript
export const state: State = {
  users: []
}
```

{% endtab %}
{% endtabs %}

## The actions file

The actions are exported individually by giving them a name and a definition.

{% tabs %}
{% tab title="overmind/posts/actions.js" %}

```typescript
export const getPosts = async () => {}

export const addNewPost = async () => {}
```

{% endtab %}

{% tab title="overmind/admin/actions.js" %}

```typescript
export const getUsers = async () => {}

export const changeUserAccess = async () => {}
```

{% endtab %}
{% endtabs %}

## The effects file

The effects are also exported individually where you would typically organize the methods in an object, but this could have been a class instance or just a plain function as well.

{% tabs %}
{% tab title="overmind/posts/effects.js" %}

```typescript
export const postsApi = {
  getPostsFromServer() {}
}
```

{% endtab %}

{% tab title="overmind/admin/effects.js" %}

```typescript
export const adminApi = {
  getUsersFromServer() {}
}
```

{% endtab %}
{% endtabs %}

You might find it more useful to define a single effects file at the root of your application and rather create a file for each effect.

{% tabs %}
{% tab title="overmind/effects/index.js" %}

```typescript
import * as api from './api'

export {
  api
}
```

{% endtab %}

{% tab title="overmind/effects/api.js" %}

```typescript
export const getUser = async () => {}

export const getPosts = async () => {}
```

{% endtab %}
{% endtabs %}

## Bring it together

Now let us export the state, actions and effects for each module and bring it all together into a **namespaced** configuration.

{% tabs %}
{% tab title="overmind/posts/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export {
  state,
  actions,
  effects
}
```

{% endtab %}

{% tab title="overmind/admin/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export {
  state,
  actions,
  effects
}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { namespaced } from 'overmind/config'
import * as posts from './posts'
import * as admin from './admin'

export const config = namespaced({
  posts,
  admin
})
```

{% endtab %}
{% endtabs %}

We used the **namespaced** function to put the state, actions and effects from each domain behind a key. In this case the key is the same as the name of the domain itself. This is an effective way to split up your app.

You can also combine this with the **merge** tool to have a top level domain.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { merge, namespaced } from 'overmind/config'
import { state } from './state'
import * as posts from './posts'
import * as admin from './admin'

export const config = merge(
  {
    state
  },
  namespaced({
    posts,
    admin
  })
)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Even though you split up into different domains each domain has access to the state of the whole application. This is an important feature of Overmind which allows you to scale up and explore the domains of the application without having to worry about isolation.
{% endhint %}


# State

Typically we think of the user interface as the application itself. But the user interface is really just there to allow a user to interact with the application. This interface can be anything. A browser window, native, sensors etc. It does not matter what the interface is, the application is still the same.

The mechanism of communicating from the application to the user interface is called **state**. A user interface is created by **transforming** the current state. To communicate from the user interface to the application an API is exposed, called **actions** in Overmind. Any interaction can trigger an action which changes the state, causing the application to notify the user interface about any updated state.

![](/files/-Ly__8wUlT2Mz5acMDgQ)

## State tree

Overmind is structured as a single state tree. That means all of your state can be accessed through a single object, called the **state**. This state tree will hold values which describes different states of your application. The tree branches out using plain objects, which can be considered **branches** of your state tree.

```javascript
{ // branch
  modes: ['issues', 'admin'],
  currentModeIndex: 0,
  admin: { // branch
    currentUserId: null,
    users: { // branch
      isLoading: false,
      data: {},
      error: null
    },
  },
  issues: { // branch
    sortBy: 'name',
    isLoading: false,
    data: {},
    error: null
  }
}
```

## State tree values

The following are values to be used with the state tree.

### Objects

The plain objects are what **branches** out the tree. It is not really considered a value in itself, it is a state branch holding values.

### Arrays

Arrays are similar to objects in the sense that they hold other values, but instead of keys pointing to values you have indexes. That means it is ideal for iteration. But more often than not objects are actually better at managing lists of values. We can actually do fine without arrays in our state. It is when we produce the actual user interface that we usually want arrays. You can learn more about this in the [MANAGING LISTS](/v23/guides-1/managing-lists) guide.

### Strings

Strings are of course used to represent text values. Names, descriptions and whatnot. But strings are also used for ids, types, etc. Strings can be used as values to reference other values. This is an important part in structuring state. For example in our **objects** example above we chose to use an array to represent the modes, using an index to point to the current mode, but we could also do:

```javascript
{
  modes: {
    issues: 0,
    admin: 1 
  },
  currentMode: 'issues'
  ...
}
```

Now we are referencing the current mode with a string. In this scenario you would probably stick with the array, but it is important to highlight that objects allow you to reference things by string, while arrays reference by number.

### Numbers

Numbers of course represent things like counts, age, etc. But just like strings, they can also represent a reference to something in a list. Like we saw in our **objects** example, to define what the current mode of our application is, we can use a number. You could say that referencing things by number works very well when the value behind the number does not change. Our modes will most likely not change and that is why an array and referencing the current mode by number, is perfectly fine.

### Booleans

Are things loading or not, is the user logged in or not? These are typical uses of boolean values. We use booleans to express that something is activated or not. We should not confuse this with **null**, which means “not existing”. We should not use **null** in place of a boolean value. We have to use either `true` or `false`.

### Null

All values, with the exception of booleans, can also be **null**. Non-existing. You can have a non-existing object, array, string or number. It means that if we haven’t selected a mode, both the string version and number version would have the value **null**.

### Derived

When you need to derive state you can add a function to your tree. Overmind treats these functions like a **getter**, but the returned value is cached and they can also access the root state of the application. A simple example of this would be:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state: State = {
  title: 'My awesome title',
  upperTitle: state => state.title.toUpperCase()
}
```

{% endtab %}
{% endtabs %}

The first argument of the function is the state the derived function is attached to. A second argument is also passed and that is the root state of the application, allowing you to access whatever you would need.

{% hint style="info" %}
Even though derived state is defined as functions you consume them as plain values. You do not have to call the derived function to get the value. Derived functions can also be dynamically added.
{% endhint %}

{% hint style="info" %}
You may use a derived for all sorts of calculations. But sometimes it's better to just use a plain action to create some state than using a derived. Why? Imagine a table component having a lot of rows and columns. We assume the table component also takes care of sorting and filtering and is capable of adding new rows. Now if you solve the sorting and filtering using a derived the following could happen: User adds a new row but it is not displayed in the list because the derived immediately kicked in and filtered it out. Thats not a good user experience. Also in this case the filtering and sorting is clearly started by a simple user interaction (setting a filter value, clicking on a column,...) so why not just start an action which creates the new list of sorted and filtered keys? Also the heavy calculation is now very predictable and doesn't cause performance issues because the derived kickes in too often (Because it could have many dependencies you might didn't think of)
{% endhint %}

### Class instances

Overmind also supports using class instances as state values. Depending on your preference this can be a powerful tool to organize your logic. What classes provide is a way to co locate state and logic for changing and deriving that state. In functional programming the state and the logic is separated and it can be difficult to find a good way to organize the logic operating on that state.

It can be a good idea to think about your classes as models. They model some state.

{% tabs %}
{% tab title="overmind/models.js" %}

```javascript
class LoginForm {
  constructor() {
    this.username = ''
    this.password = ''
  }
  get isValid() {
    return Boolean(this.username && this.password)
  }
  reset() {
    this.username = ''
    this.password = ''
  }
}
```

{% endtab %}

{% tab title="overmind/state.js" %}

```javascript
import { LoginForm } from './models'

export const state = {
  loginForm: new LoginForm()
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
It is import that you do **NOT** use arrow functions on your methods. The reason is that this binds the context of the method to the instance itself, meaning that Overmind is unable to proxy access and track mutations
{% endhint %}

You can now use this instance as normal and of course create new ones.

#### Serializing class values

If you have an application that needs to serialize the state, for example to local storage or server side rendering, you can still use class instances with Overmind. By default you really do not have to do anything, but if you use **Typescript** or you choose to use **toJSON** on your classesOvermind exposes a symbol called **SERIALIZE** that you can attach to your class.

```typescript
import { SERIALIZE } from 'overmind'

class User {
  constructor() {
    this.username = ''
    this.jwt = ''
  }
  toJSON() {
    return {
      [SERIALIZE]: true,
      username: this.username
    }
  }
}
```

If you use **Typescript** you want to add **SERIALIZE** to the class itself as this will give you type safety when rehydrating the state.

```typescript
import { SERIALIZE } from 'overmind'

class User {
  [SERIALIZE] = true
  username = ''
  jwt = ''
}
```

{% hint style="info" %}
The **SERIALIZE** symbol will not be part of the actual serialization done with **JSON.stringify**
{% endhint %}

#### Rehydrating classes

The [**rehydrate**](/v23/api-1/rehydrate) *\*\**&#x75;tility of Overmind allows you to rehydrate state either by a list of mutations or a state object, like the following:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(state, {
    user: {
      username: 'jenny',
      jwt: '123'
    }
  })    
}
```

{% endtab %}
{% endtabs %}

Since our user is a class instance we can tell rehydrate what to do, where it is typical to give the class a static **fromJSON** method:

{% tabs %}
{% tab title="overmind/models.js" %}

```typescript
import { SERIALIZE } from 'overmind'

class User {
  [SERIALIZE]
  constructor() {
    this.username = ''
    this.jwt = ''
  }
  static fromJSON(json) {
    return Object.assign(new User(), json)
  }
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(
    state,
    {
      user: {
        username: 'jenny',
        jwt: '123'
      }
    },
    {
      user: User.fromJSON
    }
  )    
}
```

{% endtab %}
{% endtabs %}

It does not matter if the state value is a class instance, an array of class instances or a dictionary of class instances, rehydrate will understand it.

That means the following will behave as expected:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
import { User } from './models'

export const state = {
  user: null, // Can be existing class instance or null
  usersList: [], // Expecting an array of values
  usersDictionary: {} // Expecting a dictionary of values
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(
    state,
    {
      user: {
        username: 'jenny',
        jwt: '123'
      },
      usersList: [{...}, {...}],
      usersDictionary: {
        'jenny': {...},
        'bob': {...}
      }
    },
    {
      user: User.fromJSON,
      usersList: User.fromJSON,
      usersDictionary: User.fromJSON
    }
  )    
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that **rehydrate** gives you full type safety when adding the **SERIALIZE** symbol to your classes. This is a huge benefit as Typescript will yell at you when the state structure changes, related to the rehydration
{% endhint %}

### Statemachines

Very often you get into a situation where you define states as **isLoading**, **hasError** etc. Having these kinds of state can cause **impossible states**. For example:

```typescript
const state = {
  isAuthenticated: true,
  isAuthenticating: true
}
```

You can not be authenticating and be authenticated at the same time. This kind of logic very often causes bugs in applications. That is why Overmind allows you to define statemachines. It sounds complicated, but is actually very simple.

#### Defining

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
import { statemachine } from 'overmind'

export const state = {
  mode: statemachine({
    initial: 'unauthenticated',
    states: {
      unauthenticated: ['authenticating'],
      authenticating: ['unauthenticated', 'authenticated'],
      authenticated: ['unauthenticating'],
      unauthenticating: ['unauthenticated', 'authenticated']
    }
  }),
  user: null,
  error: null
}
```

{% endtab %}
{% endtabs %}

You set an **initial** state and then you create a relationship between the different states and what states they can transition into. So when **unauthenticated** is the state, only logic triggered with an **authenticating** transition will run, any other transition triggered will not run its logic.

#### Transitioning

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const login = async ({ state, effects }) => {
  return state.mode.authenticating(async () => {
    try {
      const user = await effects.api.getUser()
      return state.mode.authenticated(() => {
        state.user = user
      })
    } catch (error) {
      return state.mode.unauthenticated(() => {
        state.error = error
      })    
    }
  })
}

export const logout = async ({ state, effects }) => {
  return state.mode.unauthenticating(async () => {
    try {
      await effects.api.logout()
      return state.mode.unauthenticated()
    } catch (error) {
      return state.mode.authenticated(() => {
        state.error = error
      })    
    }
  })
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
There are two important rules for predictable transitions:

1. The transition should be **returned** if the logic or logic runs asynchronously. This is the same as with actions in general
2. Only **synchronous** transitions can mutate the state, any async mutation will throw an error
   {% endhint %}

What is important to realize here is that our logic is separated into **allowable** transitions. That means when we are waiting for the user on **line 4** and some other logic has changed the state to **unauthenticated** in the meantime, the user will not be set, as the **authenticated** transition is now not possible. This is what state machines do. They group logic into states that are allowed to run, preventing invalid logic to run.

#### Current state

The current state is accessed, related to this example, by:

```typescript
state.mode.current
```

#### Exit

It is also possible to run logic when a transition exits. An example of this is for example if a transition sets up a subscription. This subscription can be disposed when the transition is exited.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const login = async ({ state, effects }) => {
  return state.mode.authenticating(async () => {
    try {
      const user = await effects.api.getUser()
      let disposeSubscription
      state.mode.authenticated(
        () => {
          disposeSubscription = effects.api.subscribeNotifications()
          state.user = user
        },
        () => {
          disposeSubscription()
        }
      )
    } catch (error) {
      state.mode.unauthenticated(() => {
        state.error = error
      })    
    }
  })
}
```

{% endtab %}
{% endtabs %}

#### Reset

You can reset the state of a statemachine, which also runs the exit of the current transition:

```typescript
state.mode.reset()
```

## References

When you add objects and arrays to your state tree, they are labeled with an “address” in the tree. That means if you try to add the same object or array in multiple spots in the tree you will get an error, as they can not have multiple addresses. Typically this indicates that you’d rather want to create a reference to an existing object or array.

So this is an example of how you would **not** want to do it:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  users: {},
  currentUser: null
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
export const setUser = ({ state }, id) => {
  state.currentUser = state.users[id]
}
```

{% endtab %}
{% endtabs %}

You’d rather have a reference to the user id, and for example use a **getter** to grab the actual user:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  users: {},
  currentUserId: null,
  get currentUser(this) {
    return this.users[this.currentUserId]
  } 
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
export const setUser = ({ state }, id) => {
  state.currentUserId = id
}
```

{% endtab %}
{% endtabs %}

## Exposing the state

We define the state of the application in **state** files. For example, the top level state could be defined as:

{% tabs %}
{% tab title="overmind/state.js" %}

```javascript
export const state = {
  isLoading: false,
  user: null
}
```

{% endtab %}
{% endtabs %}

To expose the state on the instance you can follow this recommended pattern:

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
For scalability you can define **namespaces** for multiple configurations. Read more about that in [Structuring the app](/v23/core/structuring-the-app)
{% endhint %}

## Summary

This short guide gave you some insight into how we think about state and what state really is in an application. There is more to learn about these values and how to use them to describe the application. Please move on to other guides to learn more.


# Actions

Overmind has a concept of an **action**. An action is just a function where the first argument is injected. This first argument is called the **context** and it holds the state of the application, whatever effects you have defined and references to the other actions.

You define actions under the **actions** key of your application configuration.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction = (context) => {

}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import * as actions from './actions'

export const config = {
  actions
}
```

{% endtab %}
{% endtabs %}

## Using the context

The context has three parts: **state**, **effects** and **actions**. Typically you destructure the context to access these pieces directly:

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const myAction = ({ state, effects, actions }) => {

}
```

{% endtab %}
{% endtabs %}

When you point to either of these you will always point to the “top of the application. That means if you use namespaces or other nested structures the context is always the root context of the application.

{% hint style="info" %}
The reason Overmind only has a root context is because having isolated contexts/domains creates more harm than good. Specifically when you develop your application it is very difficult to know exactly how the domains of your application will look like and what state, actions and effects belong together. By only having a root context you can always point to any domain from any other domain allowing you to easily manage cross-domain logic, not having to refactor every time your domain model breaks.
{% endhint %}

## Passing values

When you call actions you can pass a single value. This value appears as the second argument, after the context.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction = ({ state, effects, actions }, value) => {

}
```

{% endtab %}
{% endtabs %}

When you call an action from an action you do so by using the **actions** passed on the context, as this is the evaluated action that can be called.

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const myAction = ({ state, effects, actions }) => {
  actions.myOtherAction('foo')
}

export const myOtherAction = ({ state, effects, actions }, value) {

}
```

{% endtab %}
{% endtabs %}

## Organizing actions

Some of your actions will be called from the outside, publicly, maybe from a component. Other actions are only used internally, either being passed to an effect or just holding some piece of logic you want to reuse.&#x20;

There are two conventions to choose from:

### Namespace

{% tabs %}
{% tab title="overmind/internalActions.js" %}

```typescript
export const internalActionA = ({ state, effects, actions }, value) {}

export const internalActionB = async ({ state, effects, actions }) {}
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Action } from 'overmind'
import * as internalActions from './internalActions'

export const internal = internalActions

export const myAction: Action = ({ state, effects, actions }) => {
  actions.internal.internalActionA('foo')
  actions.internal.internalActionB()
}
```

{% endtab %}
{% endtabs %}

### Underscore

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction: Action = ({ state, effects, actions }) => {
  actions.internal._internalActionA('foo')
  actions.internal._internalActionB()
}

export const _internalActionA = ({ state, effects, actions }, value) {}

export const _internalActionB = async ({ state, effects, actions }) {}
```

{% endtab %}
{% endtabs %}

## Summary

The action in Overmind is a powerful concept. It allows you to define and organize logic that always has access to the core components of your application. State, effects and actions.


# Effects

Developing applications is not only about managing state, but also managing side effects. A typical side effect would be an HTTP request or talking to localStorage. In Overmind we just call these **effects**. There are several reasons why you would want to use effects:

1. All the code in your actions will be domain specific, no low level generic APIs
2. Your actions will have less code and you avoid leaking out things like URLs, types etc.
3. You decouple the underlying tool from its usage, meaning that you can replace it at any time without changing your application logic
4. You can more easily expand the functionality of an effect. For example you want to introduce caching or a base URL to an HTTP effect
5. The devtool tracks its execution
6. If you write Overmind tests, you can easily mock them
7. You can lazy-load the effect, reducing the initial payload of the app

## Exposing an existing tool

Let us just expose the [AXIOS](https://github.com/axios/axios) library as an **http** effect.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
export { default as http } from 'axios'
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export const config = {
  state,
  actions,
  effects
}
```

{% endtab %}
{% endtabs %}

We are just exporting the existing library from our effects file and including it in the application config. Now Overmind is aware of an **http** effect. It can track it for debugging and all actions and operators will have it injected.

Let us put it to use in an action that grabs the current user of the application.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const loadApp = async ({ effects, state }) => {
  state.currentUser = await effects.http.get('/user')
}
```

{% endtab %}
{% endtabs %}

That was basically it. As you can see we are exposing some low level details like the http method used and the URL. Let us follow the encouraged way of doing things and create our own **api** effect.

## Specific API

It is highly encouraged that you avoid exposing tools with their generic APIs. Rather build your own APIs that are more closely related to the domain of your application. Maybe you have an endpoint for fetching the current user. Create that as an API for your app.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
import * as axios from 'axios'

export const api = {
  getCurrentUser() {
    return axios.get<User>('/user')
  }
}
```

{% endtab %}
{% endtabs %}

Now you can see how clean your application logic becomes:

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
export const loadApp = async ({ effects, state }) => {
  state.currentUser = await effects.api.getCurrentUser()
}
```

{% endtab %}
{% endtabs %}

## Initializing effects

It can be a good idea to not allow your side effects to initialize when they are defined. This makes sure that they do not leak into tests or server side rendering. For example if you want to use Firebase, instead of initializing the Firebase application immediately we rather do it behind an **initialize** method:

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import * as firebase from 'firebase'

// We use IIFE to hide the private "app" variable
export const api = (() => {
  let app

  return {
    initialize() {
      app = firebase.initializeApp(...)      
    },
    async getPosts() {
      const snapshot = await app.database().ref('/posts').once('value')

      return snapshot.val()
    }
  }
})()
```

{% endtab %}
{% endtabs %}

We are doing two things here:

1. We use an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) to create a scoped internal variable to be used for that specific effect
2. We have created an **initialize** method which we can call from the Overmind **onInitialize** action, which runs when the Overmind instance is created

Example of initializing the effect:

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ effects }) => {
  effects.api.initialize()
  state.posts = await effects.api.getPosts()
}
```

{% endtab %}
{% endtabs %}

## Effects and state

Typically you explicitly communicate with effects from actions, by calling methods. But sometimes you need effects to know about the state of the application, or maybe some internal state in the effect should be exposed on your application state. Again we can take advantage of an **initialize** method on the effect:

{% tabs %}
{% tab title="overmind/effects.js" %}

```javascript
// We use an IIFE to isolate some variables
export const socket = (() => {
  _options
  _ws
  return {
    initialize(options) {
      _options = options
      _ws = new WebSocket('ws://...')
      _ws.onclose = () => options.onStatusChange('close')
      _ws.onopen = () => options.onStatusChange('open')
      _ws.addEventListener(
        'message',
        (event) => options.onMessage(event.data)
      )
    },
    send(type, data) {
      _ws.postMessage({
        type,
        data,
        token: _options.getToken()
      })
    }
  }
})()
```

{% endtab %}

{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ state, effects, actions }) => {
  effects.socket.initialize({
    onMessage: actions.onMessage,
    onStatusChange: actions.onSocketStatusChange,
    getToken() {
      return state.token
    }
  })
}
```

{% endtab %}
{% endtabs %}

Here we are passing in actions that can be triggered by the effect to expose internal state and/or other information that you want to manage.

## Lazy effects

You can also lazily load your effects in the **initialize** method. Let us say we wanted to load Firebase and its API on demand, or maybe just split out the code to make our app start faster.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
export const api = (() => {
  let app

  return {
    async initialize() {
      const firebase = await import('firebase')

      app = firebase.initializeApp(...)
    },
    async getPosts() {
      const snapshot = await app.database().ref('/posts').once('value')

      return snapshot.val()
    }
  }
})()
```

{% endtab %}
{% endtabs %}

In our initialize() we would just have to wait for the initialization to finish before using the API:

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ effects }) => {
  await effects.api.initialize()
  state.posts = await effects.api.getPosts()
}
```

{% endtab %}
{% endtabs %}

We could have been even bolder here making our effect download its dependency related to using any of its methods. Imagine for example the **firebase** library downloading when you run a **login** method on the effect.

## Configurable effect

By defining a class we can improve testability, allow using environment variables and even change out the actual implementation.

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import axios from 'axios'

export class Api {
  private baseUrl
  private request
  constructor (baseUrl, request) {
    this.baseUrl = baseUrl
    this.request = request
  }
  getCurrentUser()  {
    return this.request.get(`${this.baseUrl}/user`)
  }
}

export const api = new Api(IS_PRODUCTION ? '/api/v1' : 'http://localhost:4321', axios)
```

{% endtab %}
{% endtabs %}

We export an instance of our **Api** to the application. This allows us to also create instances in isolation for testing purposes, making sure our Api class works as we expect.

## Summary

Importing side effects directly into your code should be considered bad practice. If you think about it from an application standpoint it is kinda weird that it runs HTTP verb methods with a URL string passed in. It is better to create an abstraction around it to make your code more consistent with the domain, and by doing so also improve maintainability.


# Operators

You get very far building your application with straightforward imperative actions. This is typically how we learn programming and is arguably close to how we think about the world. But this approach can cause you to overload your actions with imperative code, making them more difficult to read and especially reuse pieces of logic. As the complexity of your application increases you will find benefits to doing some of your logic, or maybe all your logic, in a functional style.

Let us look at a concrete example of how messy an imperative approach would be compared to a functional approach.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
let debounce
export const search = ({ state, effects }, event) => {
  state.query = event.currentTarget.value

  if (query.length < 3) return

  if (debounce) clearTimeout(debounce)

  debounce = setTimeout(async () => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false

    debounce = null
  }, 200)
}
```

{% endtab %}
{% endtabs %}

What we see here is an action trying to express a search. We only want to search when the length of the query is more than 2 characters and we only want to trigger the search when the user has not changed the query for 200 milliseconds.

If we were to do this in a functional style it would look more like this:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import { pipe, debounce, mutate, filter } from 'overmind'

export const search = pipe(
  mutate(({ state }, value) => {
    state.query = value
  }),
  filter(({ state }) => state.query.length > 2),
  debounce(200),
  mutate(({ state, effects }) => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false
  })
)
```

{% endtab %}
{% endtabs %}

As you can see our action is described more declaratively. We could have moved each individual piece of logic, each operator, into a different file. All these operators could now be reused in other action compositions.

## Structuring operators

You will typically rely on an **operators** file where all your composable pieces live. Inside your **actions** file you expose the operators and compose them together using **pipe** and other *composing* operators. This approach ensures:

1. Each operator is defined separately and in isolation
2. The action composed of operators is defined with the other actions
3. The action composed of operators is declarative (no inline operators with logic)

Let us look at how the operators in the search example could have been implemented:

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {filter, mutate } from 'overmind'

export const setQuery = () =>
  mutate(function setQuery({ state }, query) {
    state.query = query
  })

export const lengthGreaterThan = (length) =>
  filter(function lengthGreaterThan(_, value) {
    return value.length > length
  })

export const getSearchResult = () => 
  mutate(async function getSearchResult({ state, effects }, query) {
    state.isSearching = true
    state.searchResult = await effects.api.search(query)
    state.isSearching = false
  })
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that we give all the actual operator functions the same name as the exported variable that creates it. The reason is that this name is picked up by the devtools and gives you more insight into how your code runs.
{% endhint %}

You might wonder why we define the operators as functions that we call. We do that for the following reasons:

1. It ensures that each composition using the operator has a unique instance of that operator. For most operators this does not matter, but for others like **debounce** it actually matters.
2. Some operators require options, like the **lengthGreaterThan** operator we created above. Defining all operators as functions just makes things more consistent.
3. If you were to create an operator that is composed of other operators you can safely do so without thinking about the order of definition in the *operators* file. The reason being that the operator is lazily created
4. With Typescript it opens up to partial and generic typed operators. Read more about this in the [Typescript](/v23/core/typescript) guide

Now, you might feel that we are just adding complexity here. An additional file with more syntax. But clean and maintainable code is not about less syntax. It is about structure, predictability and reusability. What we achieve with this functional approach is a super readable abstraction in our *actions* file. There is no logic there, just references to logic. In our *operators* file each piece of logic is defined in isolation with very little logic.

## Calling operators

You typically compose the different operators together with **pipe** and **parallel** in the *actions* file, but any operator can actually be exposed as an action. With the search example:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import {pipe, debounce, mutate, filter } from 'overmind'

export const search = pipe(
  mutate(({ state }, value) => {
    state.query = value
  }),
  filter(({ state }) => state.query.length > 2),
  debounce(200),
  mutate(({ state, effects }) => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false
  })
)
```

{% endtab %}
{% endtabs %}

You would call this action like any other:

```typescript
overmind.actions.search("something")
```

## Inputs and Outputs

To produce new values throughout your pipe you can use the **map** operator. It will put whatever value you return from it on the pipe for the next operator to consume.

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {map, mutate } from 'overmind'

export const toNumber = () =>
  map(function toNumber(_, value) { 
    return Number(value)
  })

export const setValue = () =>
  mutate(function setValue({ state}, value) {
    state.value = value
  })
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import {pipe } from 'overmind'
import * as o from './operators'

export const onValueChange = pipe(
  o.toNumber(),
  o.setValue()
)
```

{% endtab %}
{% endtabs %}

## Custom operators

The operators concept of Overmind is based on the [OP-OP SPEC](https://github.com/christianalfoni/op-op-spec), which allows for endless possibilities in functional composition. But since Overmind does not only pass values through these operators, but also the context where you can change state, run effects etc., we want to simplify how you can create your own operators. The added benefit of this is that the operators you create are also tracked in the devtools.

### toUpperCase <a href="#create-custom-operators-touppercase" id="create-custom-operators-touppercase"></a>

Let us create an operator that simply uppercases the string value passed through. This could easily have been done using the **map** operator, but for educational purposes let us see how we can create our very own operator.

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {createOperator, mutate } from 'overmind'

export const toUpperCase = () => {
  return createOperator('toUpperCase', '', (err, context, value, next) => {
    if (err) next(err, value)
    else next(null, value.toUpperCase())
  })
}

export const setTitle = mutate(({ state }, title) => {
  state.title = title
})
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { pipe } from 'overmind'
import { toUpperCase, setTitle } from './operators'

export const setUpperCaseTitle = pipe(
  toUpperCase(),
  setTitle
)
```

{% endtab %}
{% endtabs %}

We first create a function that returns an operator when we call it. We pass this operator a **name**, an optional **description** and the callback that is executed when the operator runs. This operator might receive an **error**, that you can handle if you want to. It also receives the **context**, the current **value** and a function called **next**.

In this example we did not use the **context** because we are not going to look at any state, run effects etc. We just wanted to change the value passed through. All operators need to handle the **error** in some way. In this case we just pass it along to the next operator by calling **next** with the error as the first argument and the current value as the second. When there is no error it means we can manage our value and we do so by calling **next** again, but passing **null** as the first argument, as there is no error. And the second argument is the new **value**.

### operations <a href="#create-custom-operators-operations" id="create-custom-operators-operations"></a>

You might want to run some logic related to your operator. Typically this is done by giving a callback. You can provide this callback whatever information you want, even handle its return value. So for example the **map** operator is implemented like this:

```typescript
import { createOperator } from 'overmind'

export function map(operation) {
  return createOperator(
    'map',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else next(null, operation(context, value))
    }
  )
}
```

### mutations <a href="#create-custom-operators-mutations" id="create-custom-operators-mutations"></a>

You can also create operators that have the ability to mutate the state, it is just a different factory **createMutationFactory**. This is how the **mutate** operator is implemented:

```typescript
import { createMutationOperator } from 'overmind'

export function mutate(operation) {
  return createMutationOperator(
    'mutate',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else {
        operation(context, value)
        next(null, value)
      }
    }
  )
}
```

### paths <a href="#create-custom-operators-paths" id="create-custom-operators-paths"></a>

You can even manage paths in your operator. This is how the **when** operator is implemented:

```typescript
import { createOperator } from 'overmind'

export function when(operation, paths) {
  return createOperator(
    'when',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else if (operation(context, value))
        next(null, value, {
          name: 'true',
          operator: paths.true,
        })
      else
        next(null, value, {
          name: 'false',
          operator: paths.false,
        })
    }
  )
}
```

### aborting <a href="#create-custom-operators-aborting" id="create-custom-operators-aborting"></a>

Some operators want to prevent further execution. That is also possible to implement, as seen here with the **filter** operator:

```typescript
import { createOperator } from 'overmind'

export function filter(operation) {
  return createOperator(
    'filter',
    operation.name,
    (err, context, value, next, final) => {
      if (err) next(err, value)
      else if (operation(context, value)) next(null, value)
      else final(null, value)
    }
  )
}
```

The **final** argument bypasses any other operators.


# Statecharts

Just like [OPERATORS](/v23/core/going-functional) is a declarative abstraction over plain actions, **statecharts** is a declarative abstraction over an Overmind configuration of **state** and **actions**. That means you will define your charts by:

```typescript
const configWithStatechart = statechart(config, chart)
```

There are several benefits to using statecharts:

1. You will have a declarative description of what actions should be available in certain states of the application
2. Less bugs because an invalid action will not be executed if called
3. You will be able to implement and test an interaction flow without building the user interface for it
4. Your state definition is cleaned up as your **isLoading** types of state is no longer needed
5. You have a tool to do “top down” implementation instead of “bottom up”

You can basically think of a statechart as a way of limiting what actions are available to be executed in certain states of the application. This concept is very old and was originally used to design machines where the user was exposed to all points of interaction, all buttons and switches, at any time. Statecharts would help make sure that at certain states certain buttons and switches would not operate.

A simple example of this is a Walkman. When the Walkman is in a **playing** state you should not be able to hit the **eject** button. On the web this might seem unnecessary as points of interaction is dynamic. We simply hide and/or disable buttons. But this is the exact problem. It is fragile. It is fragile because the UI implementation itself is all you depend on to prevent logic from running when it should not. A statechart is a much more resiliant way to ensure what logic can actually run in any given state.

In Overmind we talk about these statechart states as **transition states**.

## Defining a statechart

Let us imagine that we have a login flow. This login flow has 4 different **transition states**:

1. **LOGIN**. We are at the point where the user inserts a username and password
2. **AUTHENTICATING**. The user has submitted
3. **AUTHENTICATED**. The user has successfully logged in
4. **ERROR**. Something wrong happened

Let us do this properly and design this flow “top down”:

{% tabs %}
{% tab title="overmind/login/index.js" %}

```typescript
import { statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const loginChart = {
  initial: 'LOGIN',
  states: {
    LOGIN: {
      on: {
        changeUsername: null,
        changePassword: null,
        login: 'AUTHENTICATING'
      }
    },
    AUTHENTICATING: {
      on: {
        resolveUser: 'AUTHENTICATED',
        rejectUser: 'ERROR'
      }
    },
    AUTHENTICATED: {
      on: {
        logout: 'LOGIN'
      }
    },
    ERROR: {
      on: {
        tryAgain: 'LOGIN'
      }
    }
  }
}

export default statechart(config, loginChart)
```

{% endtab %}
{% endtabs %}

As you can see we have defined what transition states our login flow can be in and what actions we want available to us in each transition state. If the action points to **null** it means we stay in the same transition state. If it points to an other transition state, the execution of that action will cause that transition to occur.

Since our initial state is **LOGIN**, a call to actions defined in the other transition states would simply be ignored.

{% hint style="info" %}
You might expect actions to throw an error if they are called, but not allowed to do so. This is not the case with statecharts. During development you will get a warning when this happens, but in production absolutely nothing happens. Hitting a submit button multiple times might be perfectly okay, but after the first submit the chart moves to a new state, preventing any further execution of logic on the following submits.
{% endhint %}

## Transitions

If you are familiar with the concept of statemachines you might ask the question: *“Where are the transitions?”*. In Overmind we use actions to define transitions instead of having explicit transition types. That means you think about statecharts in Overmind as:

```
TRANSITION STATE -> ACTION -> NEW TRANSITION STATE
```

as opposed to:

```
TRANSITION STATE -> TRANSITION TYPE -> { NEW TRANSITION STATE, ACTION }
```

This approach has three benefits:

1. It is more explicit in the definition that a transition state configures what actions are available
2. When typing your application the actions already has a typed input, which would not be possible with a generic **transition** action
3. It is simpler concept both in code and for your brain

What to take notice of is that the **action** causing the transition is run before the transition actually happens. That means the action runs in the context of the current transition state and any synchronous calls to another action will obey its rules. If the action does something asynchronous, like doing an HTTP request, the transition will be performed and the asynchronous logic will run in the context of the new transition state.

```typescript
const myTransitionAction = async ({ actions }) => {
  // I am still in the current transition state
  actions.someOtherAction()

  await Promise.resolve()

  // I am in the new transition state
  actions.someOtherAction()
}
```

## Nested statecharts

With a more complicated UI we can create nested statecharts. An example of this would be a workspace UI with different tabs. You only want to allow certain actions when the related tab is active. Let us explore an example:

{% tabs %}
{% tab title="overmind/dashboard/index.js" %}

```typescript
import { statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const issuesChart = {
  initial: 'LOADING',
  states: {
    LOADING: {
      entry: 'fetchIssues',
      exit: 'abortFetchIssues',
      on: {
        resolveIssues: 'LIST',
        rejectIssues: 'ERROR'
      }
    },
    LIST: {
      on: {
        toggleIssueCompleted: null
      }
    },
    ERROR: {
      on: {
        retry: 'LOADING'
      }
    },
  }
}

const projectsChart = {
  initial: 'LOADING',
  states: {
    LOADING: {
      entry: 'fetchProjects',
      exit: 'abortFetchProjects',
      on: {
        resolveIssues: 'LIST',
        rejectIssues: 'ERROR'
      }
    },
    LIST: {
      on: {
        expandAttendees: null
      }
    },
    ERROR: {
      on: {
        retry: 'LOADING'
      }
    },
  }
}

const dashboardChart = {
  initial: 'ISSUES',
  states: {
    ISSUES: {
      on: {
        openProjects: 'PROJECTS'
      },
      chart: issuesChart
    },
    PROJECTS: {
      on: {
        openIssues: 'ISSUES'
      },
      chart: projectsChart
    }
  }
}

export default statechart(config, dashboardChart)
```

{% endtab %}
{% endtabs %}

What to take notice of in this example is that all chart states has its own **chart** property, which allows them to be nested. The nested charts has access to the same actions and state as the parent chart.

In this example we also took advantage of the **entry** and **exit** hooks of a transition state. These also points to actions. When a transition is made into the transition state, the **entry** will run. This behavior is nested. When an **exit** hook exists and a transition is made away from the transition state, it will also run. This behavior is also nested of course.

## Parallel statecharts

It is also possible to define your charts in a parallel manner. You do this by simply using an object of keys where the key represents an ID of the chart. The **chart** property on a transition state allows the same. Either a single chart or an object of multiple charts where the key represents an ID of the chart.

```typescript
export default statechart(config, {
  issues: issuesChart,
  projects: projectsChart
})
```

## Conditions

In our chart above we let the user log in even though there is no **username** or **password**. That seems a bit silly. In statecharts you can define conditions. These conditions receives the state of the configuration and returns true or false.

{% tabs %}
{% tab title="overmind/login/index.js" %}

```typescript
import {statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const loginChart = {
  initial: 'LOGIN',
  states: {
    LOGIN: {
      on: {
        changeUsername: null,
        changePassword: null,
        login: {
          target: 'AUTHENTICATING',
          condition: state => Boolean(state.username && state.password)
        }
      }
    },
    ...
  }
}

export default statechart(config, loginChart)
```

{% endtab %}
{% endtabs %}

Now the **login** action can only be executed when there is a username and password inserted, causing a transition to the new transition state.

## State

Our initial state defined for this configuration is:

{% tabs %}
{% tab title="overmind/login/state.js" %}

```typescript
export const state = {
  username: '',
  password: '',
  user: null,
  authenticationError: null
}
```

{% endtab %}
{% endtabs %}

As you can see we have no state indicating that we have received an error, like **hasError**. We do not have **isLoggingIn** either. There is no reason, because we have our transition states. That means the configuration is populated with some additional state by the statechart. It will actually look like this:

```typescript
{
  username: '',
  password: '',
  user: null,
  authenticationError: null,
  states: [['CHART', 'LOGIN']],
  actions: {
    changeUsername: true,
    changePassword: true,
    login: false,
    logout: false,
    tryAgain: false
  }
}
```

The **states** state is the current transition states. It is defined as an array of arrays. This indicates that we can have parallel and nested charts. The **CHART** symbol in the array indicates that you have defined an immediate chart. If you rather defined parallel charts you would define your own ids.

The **actions** state is a derived state. That means it automatically updates based on the current state of the chart. This is helpful for your UI implementation. It can use it to disable buttons etc. to help the user understand when certain actions are possible.

### Identifying states <a href="#statecharts-identifying-states" id="statecharts-identifying-states"></a>

There is also a third derived state called **matches**. This derived state returns a function that allows you to figure out what state you are in. This is also the API you use in your components to identify the state of your application:[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/guide/statecharts/matches.ts.ts)

```typescript
state.login.matches({
  LOGIN: true
})
```

You can also do more complex matches related to parallel and nested charts:[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/guide/statecharts/matches_multiple.ts.ts)

```typescript
// Nested
const isSearching = state.dashboard.matches({
  LIST: {
    search: {
      SEARCHING: true
    }
  }
})

// Parallel
const isDownloadingAndUploading = state.files.matches({
  download: {
    LOADING: true
  },
  upload: {
    LOADING: true
  }
})

// Complex match
const isOnlyDownloading = state.files.matches({
  download: {
    LOADING: true
  },
  upload: {
    LOADING: false
  }
})
```

### Actions <a href="#statecharts-actions" id="statecharts-actions"></a>

Our actions are defined something like:

{% tabs %}
{% tab title="overmind/login/actions.js" %}

```typescript
export const changeUsername = ({ state }, username) => {
  state.login.username = username
}

export const changePassword = ({ state }, password) => {
  state.login.password = password
}

export const login = ({ state, actions, effects }) => {
  try {
    const user = await effects.api.login(state.username, state.password)
    actions.login.resolveUser(user)
  } catch (error) {
    actions.login.rejectUser(error)
  }
}

export const resolveUser = ({ state }, user) => {
  state.login.user = user
}

export const rejectUser = ({ state }, error) => {
  state.login.authenticationError = error.message
}

export const logout = ({ effects }) => {
  effects.api.logout()
}

export const tryAgain = () => {}
```

{% endtab %}
{% endtabs %}

What to take notice of here is that with traditional Overmind we would most likely just set the **user** or the **authenticationError** directly in the **login** action. That is not the case with statcharts because our actions are the triggers for transitions. That means whenever we want to deal with transitions we create an action for it, even completely empty actions like **tryAgain**. This simplifies our chart definition and also we avoid having a generic **transition** action that would not be typed in TypeScript.

Now these two charts would operate individually. This is also the case for the **chart** property on the states of a chart.

## Devtools

The Overmind devtools understands statecharts. That means you are able to get an overview of available statecharts and even manipulate them directly in the devtools.

![](/files/-LyeAtF5_zJ45kWzFpgY)

You will see what transition states and actions are available, and active, within each of them. You can click any active action to select it and click again to execute, or insert at payload at the top before execution.

## Summary

The point of statecharts in Overmind is to give you an abstraction over your configuration that ensures the actions can only be run in certain states. Just like operators you can choose where you want to use it. Maybe only one namespace needs a statechart, or maybe you prefer using it on all of them. The devtools has its own visualizer for the charts, which allows you to implement and test them without implementing any UI.w


# Server Side Rendering

Some projects require you to render your application on the server. There are different reasons to do this, like search engine optimizations, general optimizations and even browser support. What this means for state management is that you want to expose a version of your state on the server and render the components with that state. But that is not all, you also want to **hydrate** the changed state and pass it to the client with the HTML so that it can **rehydrate** and make sure that when the client renders initially, it renders the same UI.

## Preparing the project

When doing server-side rendering the configuration of your application will be shared by the client and the server. That means you need to structure your app to make that possible. There is really not much you need to do.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { state } from './state'

export const config = {
  state
}

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}

{% tab title="index.ts" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

Here we only export the configuration from the main Overmind file. The instantiation rather happens where we prepare the application on the client side. That means we can now safely import the configuration also on the server.

## Preparing effects

The effects will also be shared with the server. Typically this is not an issue, but you should be careful about creating effects that run logic when they are defined. You might also consider lazy-loading effects so that you avoid loading them on the server at all. You can read more about them in [EFFECTS](/v23/core/running-side-effects).

## Rendering on the server

When you render your application on the server you will have to create an instance of Overmind designed for running on the server. On this instance you can change the state and provide it to your components for rendering. When the components have rendered you can **hydrate** the changes and pass them along to the client so that you can **rehydrate**.

{% hint style="info" %}
Overmind does not hydrate the state, but the mutations you performed. That means it minimizes the payload passed over the wire.
{% endhint %}

The following shows a very simple example using an [EXPRESS](https://expressjs.com/) middleware to return a server side rendered version of your app.

{% tabs %}
{% tab title="server/routePosts.ts" %}

```typescript
import { createOvermindSSR } from 'overmind'
import { config } from '../client/overmind'
import db from './db'

export default async (req, res) => {
  const overmind = createOvermindSSR(config)

  overmind.state.currentPage = 'posts'
  overmind.state.posts = await db.getPosts()

  const html = renderToString(
    // Whatever implementation your view layer provides
  )

  res.send(`
<html>
  <body>
    <div id="app">${html}</div>
    <script>
      window.__OVERMIND_MUTATIONS = ${JSON.stringify(overmind.hydrate())}
    </script>
    <script src="/scripts/app.js"></script>
  </body>
</html>
`)
}
```

{% endtab %}
{% endtabs %}

## Rehydrate on the client

On the client you just want to make sure that your Overmind instance rehydrates the mutations performed on the server so that when the client renders, it does so with the same state. The **onInitialize** hook of Overmind is the perfect spot to do this.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize, rehydrate } from 'overmind'

export const onInitialize: OnInitialize = ({ state }) => {
  const mutations = window.__OVERMIND_MUTATIONS

  rehydrate(state, mutations)
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
If you are using state first routing, make sure you prevent the router from firing off the initial route, as this is not needed.
{% endhint %}

## OnInitialize

The `onInitialized` action does not run on the server. The reason is that it is considered a side effect you might not want to run, so we do not force it. If you do want to run an action as Overmind fires up both on the client and the server you can rather create a custom action for it.

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const initialize = () => {
  // Whatever...
}
```

{% endtab %}

{% tab title="client/index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
overmind.actions.initialize()
```

{% endtab %}

{% tab title="server/index.js" %}

```javascript
import { createOvermindSSR } from 'overmind'
import { config } from '../client/overmind'

export default async (req, res) => {
  const overmind = createOvermindSSR(config)
  await overmind.actions.initialize()

  const html = renderToString(
    // Whatever implementation your view layer provides
  )

  res.send(`
<html>
  <body>
    <div id="app">${html}</div>
    <script>
      window.__OVERMIND_MUTATIONS = ${JSON.stringify(overmind.hydrate())}
    </script>
    <script src="/scripts/app.js"></script>
  </body>
</html>
`)
}
```

{% endtab %}
{% endtabs %}


# Typescript

Overmind is written in Typescript and it is written with a focus on you dedicating as little time as possible to help Typescript understand what your app is all about. Typescript will spend a lot more time helping you. If you are not a Typescript developer Overmind is a really great project to start learning it as you will get the most out of the little typing you have to do.

## Configuration

First we need to define the typing of our configuration and there are two approaches to that.

### 1. Declare module

The most straightforward way to type your application is to use the **declare module** approach. This will work for most applications, but might make you feel uncomfortable as a hardcore Typescripter. The reason is that we are overriding an internal type, meaning that you can only have one instance of Overmind running inside your application.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'

const config = {}

declare module 'overmind' {
  // tslint:disable:interface-name
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}

Now you can import any type directly from Overmind and it will understand the configuration of your application. Even the operators are typed.

```typescript
import {
  Action,
  Operator,
  Derive,
  pipe,
  map,
  filter,
  ...
} from 'overmind'
```

### 2. Explicit typing

You can also explicitly type your application. This gives more flexibility.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import {
  IConfig,
  IOnInitialize,
  IAction,
  IOperator,
  IDerive,
  IState
} from 'overmind'

export const config = {}

export interface Config extends IConfig<typeof config> {}

export interface OnInitialize extends IOnInitialize<Config> {}

export interface Action<Input = void, Output = void> extends IAction<Config, Input, Output> {}

export interface AsyncAction<Input = void, Output = void> extends IAction<Config, Input, Promise<Output>> {}

export interface Operator<Input = void, Output = Input> extends IOperator<Config, Input, Output> {}

export interface Derive<Parent extends IState, Output> extends IDerive<Config, Parent, Output> {}
```

{% endtab %}
{% endtabs %}

You only have to set up these types once, where you bring your configuration together. That means if you use multiple namespaced configuration you still only create one set of types, as shown above.

Now you only have to make sure that you import your types from this file, instead of directly from the Overmind package.

{% hint style="info" %}
The Overmind documentation is written for implicit typing. That means whenever you see a type import directly from the Overmind package, you should rather import from your own defined types.
{% endhint %}

## State

The state you define in Overmind is just an object where you type that object.

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
type State = {
  foo: string
  bar: boolean
  baz: string[]
  user: User
}

export const state: State = {
  foo: 'bar',
  bar: true,
  baz: [],
  user: new User()
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
It is important that you use a **type** and not an **interface.** This has to do with the way Overmind resolves the state typing.&#x20;
{% endhint %}

When writing Typescript you should **not** use optional values for your state (**?**), or use **undefined** in a union type. In a serializable state store world **null** is the value indicating *“there is no value”.*

```typescript
type State = {
  // Do not do this
  foo?: string

  // Do not do this
  foo: string | undefined

  // Do this
  foo: string | null

  // Or this, if there always will be a value there
  foo: string
}

export const state: State = {
  foo: null
}
```

### Getter

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
type State = {
  foo: string
  shoutedFoo string
}

export const state: State = {
  foo: 'bar',
  get shoutedFoo(this: State) {
    return this.foo + '!!!'
  }
}
```

{% endtab %}
{% endtabs %}

### Derived

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { derived } from 'overmind'

type State = {
  foo: string
  shoutedFoo string
}

export const state: State = {
  foo: 'bar',
  shoutedFoo: derived<State, string>(state => state.foo + '!!!')
}
```

{% endtab %}
{% endtabs %}

Note that the type argument you pass is the object the derived is attached to, so with nested derived:

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { derived } from 'overmind'

type State = {
  foo: string
  nested: {
    shoutedFoo string
  }
}

export const state: State = {
  foo: 'bar',
  nested: {
    shoutedFoo: derived<State['nested'], string>(state => state.foo + '!!!')
  }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Note that with **Explicit Typing** you need to also pass the a third argument to the **derived** function, the **Config** type created in your main **index.ts** file.
{% endhint %}

## Actions

The action type takes either an input type, an output type, or both.

```typescript
import { Action } from 'overmind'

export const noArgAction: Action = (context, value) => {
  value // this becomes "void"
}

export const argAction: Action<string> = (context, value) => {
  value // this becomes "string"
}

export const noArgWithReturnTypeAction: Action<void, string> = (context, value) => {
  value // this becomes "void"

  return 'foo'
}

export const argWithReturnTypeAction: Action<string, string> = (context, value) => {
  value // this becomes "string"

  return value + '!!!'
}
```

You also have an **async** version of this type. You use this when you want to define an **async** function, which implicitly returns a promise, or use it on a function that explicitly returns a promise.

```typescript
import { AsyncAction } from 'overmind'

export const noArgAction: AsyncAction = async (context, value) => {
  value // this becomes "void"
}

export const argAction: AsyncAction<string> = async (context, value) => {
  value // this becomes "string"
}

export const noArgWithReturnTypeAction: AsyncAction<void, string> = async (context, value) => {
  value // this becomes "void"

  return 'foo'
} // returns Promise<string>

export const argWithReturnTypeAction: AsyncAction<string, string> = (context, value) => {
  value // this becomes "string"

  return Promise.resolve(value + '!!!')
} // returns Promise<string>
```

## Effects

There are no Overmind specific types related to effects, you just type them in general.

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
export const api = {
  getUser: async (): Promise<User> => {
    const response = await fetch('/user')
    
    return response.json()
  }
}
```

{% endtab %}
{% endtabs %}

## Operators

Operators is like the **Action** type: it can take an optional input, but it always produces an output. By default the output of an operator is the same as the input.

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, mutate, filter, map } from 'overmind'

// You do not need to define any types, which means it defaults
// its input and output to "void"
export const changeSomeState: () => Operator = () =>
  mutate(function changeSomeState({ state }) {
    state.foo = 'bar'
  })

// The second type argument is not set, but will default to "User"
// The output is the same as the input
export const filterAwesomeUser: () => Operator<User> = () =>
  filter(function filterAwesomeUser(_, user) {
    return user.isAwesome
  })

// "map" produces a new output so we define that as the second
// type argument
export const toNumber: () => Operator<string, number> = () =>
  map(function toNumber(_, value) { 
    return Number(value)
  })
```

{% endtab %}
{% endtabs %}

The **Operator** type is used to type all operators. The type arguments you give to **Operator** have to match the specific operator you use though. So for example if you type a **mutate** operator with a different output than the input:

```typescript
import { Operator, mutate } from 'overmind'

export const doThis: () => Operator<string, number> = () => 
  mutate(function doThis() {

  })
```

Typescript yells at you, because this operator just passes the value straight through.

Typically you do not think about this and Typescript rather yells at you when the value you are passing through your operators is not matching up.

### Generic input

You might create an operator that does not care about its input. For example:

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, mutate } from 'overmind'

export const doSomething: () => Operator = () =>
  mutate(function doSomething({ state }) {
    state.foo = 'bar'
  })
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe, action } from 'overmind'
import * as o from './operators'

export const setInput: Operator<string> = pipe(
  o.doSomething(),
  o.setValue()
)
```

{% endtab %}
{% endtabs %}

Composing **doSomething** into the **pipe** gives an error, cause the action is typed with a **string** input, but the **doSomething** operator is typed with **void**.

To fix this we just add a generic type to the definition of our operator:

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, mutate } from 'overmind'

export const doSomething: <T>() => Operator<T> = () =>
  mutate(function doSomething({ state }) {
    state.foo = 'bar'
  })
```

{% endtab %}
{% endtabs %}

Now Typescript infers the input type of the operator and passes it along.

### Partial input

For example:

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, filter } from 'overmind'

export const filterAwesome: () => Operator<{ isAwesome: boolean }> = () =>
  filter(function filterAwesome(_, somethingAwesome) {
    return somethingAwesome.isAwesome
  })
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe, action } from 'overmind'
import * as o from './operators'
import { User } from './state'

export const clickedUser: Operator<User> = pipe(
  o.filterAwesome(),
  o.handleAwesomeUser()
)
```

{% endtab %}
{% endtabs %}

Now the *input* is actually okay, because `{ isAwesome: boolean }` matches the **User** type, but we are also now saying that the type of *output* will be `{ isAwesome: boolean }`, which does not match the **User** type required by **handleAwesomeUser**.

To fix this we again infer the type, but using **extends** to indicate that we do have a requirement to the type it should pass through:

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, filter } from 'overmind'

export const filterAwesome: <T extends { isAwesome: boolean }>() => Operator<T> =
  () => filter(function filterAwesome(_, somethingAwesome) {
    return somethingAwesome.isAwesome
  })
```

{% endtab %}
{% endtabs %}

That means this operator can handle any type that matches an **isAwesome** property, though will pass the original type through.

## Statemachine

Statemachines exposes a type called **Statemachine** which you will give a single type argument of what states it should manage:

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { Statemachine, statemachine } from 'overmind'

type Mode =
  | 'unauthenticated'
  | 'authenticating'
  | 'authenticated'
  | 'unauthenticating'

type State = {
  mode: Statemachine<Mode>
}

export const state: State = {
  mode: statemachine<Mode>({
    initial: 'unauthenticated',
    states: {
      unauthenticated: ['authenticating'],
      authenticating: ['unauthenticated', 'authenticated'],
      authenticated: ['unauthenticating'],
      unauthenticating: ['unauthenticated', 'authenticated']
    }
  })
}
```

{% endtab %}
{% endtabs %}

## Statechart

To type a statechart you use the **Statechart** type:

{% tabs %}
{% tab title="overmind/someNamespace/index.ts" %}

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const someChart: Statechart<typeof config, {
  FOO: void
  BAR: void
}> = {
  initial: 'FOO',
  states: {
    FOO: {},
    BAR: {}
  }
}

export default statechart(config, someChart)
```

{% endtab %}
{% endtabs %}

The **void** type just defines that there are no nested charts. All the states and points of inserting an action name is now typed. Also the **condition** callback is typed. Even the **matches** API is typed correctly.

### Nested chart

{% tabs %}
{% tab title="overmind/someNamespace/index.ts" %}

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const someNestedChart: Statechart<typeof config, {
  NESTED_FOO: void
  NESTED_BAR: void
}> = {
  initial: 'NESTED_FOO',
  states: {
    NESTED_FOO: {},
    NESTED_BAR: {}
  }
}

const someChart: Statechart<typeof config, {
  FOO: typeof someNestedChart
  BAR: void
}> = {
  initial: 'FOO',
  states: {
    FOO: {
      chart: someNestedChart
    },
    BAR: {}
  }
}

export default statechart(config, someChart)
```

{% endtab %}
{% endtabs %}

## Linting

When you are using TSLint it is important that you use the official [MICROSOFT EXTENSION](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-tslint-plugin) for VS Code.


# React

There are two different ways to connect Overmind to React. You can either use a traditional **Higher Order Component** or you can use the new **hooks** api to expose state and actions.

When you connect Overmind to a component you ensure that whenever any tracked state changes, only components interested in that state will re-render, and will do so “at their location in the component tree”. That means we remove a lot of unnecessary work from React. There is no reason for the whole React component tree to re-render when only one component is interested in a change.

## Hook

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

```typescript
// overmind/index.js
import { createHook } from 'overmind-react'
import { state } from './state'
import * as actions from './actions'

export const config = {
  state,
  actions
}

export const useOvermind = createHook()

// index.js
import * as React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import App from './components/App'

const overmind = createOvermind(config)

render((
  <Provider value={overmind}>
    <App />
  </Provider>
), document.querySelector('#app'))

// components/App.jsx
import * as React from 'react'
import { useOvermind } from '../overmind'

const App = () => {
  const { state, actions, effects, reaction } = useOvermind()

  return <div />
}

export default App
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// overmind/index.ts
import { IConfig } from 'overmind'
import { createHook } from 'overmind-react'
import { state } from './state'
import * as actions from './actions'

export const config = {
  state,
  actions
}

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}

export const useOvermind = createHook<typeof config>()

// index.tsx
import * as React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import App from './components/App'

const overmind = createOvermind(config)

render((
  <Provider value={overmind}>
    <App />
  </Provider>
), document.querySelector('#app'))

// components/App.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'

const App: React.FunctionComponent = () => {
  const { state, actions, effects, reaction } = useOvermind()

  return <div />
}

export default App
```

{% endtab %}
{% endtabs %}

### Rendering

When you use the Overmind hook it will ensure that the component will render when any tracked state changes. It will not do anything related to the props passed to the component. That means whenever the parent renders, this component renders as well. You will need to wrap your component with [**REACT.MEMO**](https://reactjs.org/docs/react-api.html#reactmemo) to optimize rendering caused by a parent.

### Passing state as props

If you pass a state object or array as a property to a child component you will also in the child component need to use the **useOvermind** hook to ensure that it is tracked within that component, even though you do not access any state or actions. The devtools will help you identify where any components are left “unconnected”.

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

```typescript
// components/Todos.jsx
import * as React from 'react'
import { useOvermind } from '../overmind'
import Todo from './Todo'

const Todos = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.todos.map(todo => <Todo key={todo.id} todo={todo} />)}
    </ul<
  )
}

export default Todos

// components/Todo.jsx
import * as React from 'react'
import { useOvermind } from '../overmind'

const Todo = ({ todo }) => {
  useOvermind()

  return <li>{todo.title}</li>
}

export default Todo
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// components/Todos.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'
import Todo from './Todo'

const Todos: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.todos.map(todo => <Todo key={todo.id} todo={todo} />)}
    </ul<
  )
}

export default Todos

// components/Todo.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'

type Props = {
  todo: Todo
}

const Todo: React.FunctionComponent<Props> = ({ todo }) => {
  useOvermind()

  return <li>{todo.title}</li>
}

export default Todo
```

{% endtab %}
{% endtabs %}

### Reactions

The hook effect of React gives a natural point of running effects related to state changes. An example of this is from the Overmind website, where we scroll to the top of the page whenever the current page state changes.

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

```typescript
// components/App.jsx
import * as React from 'react'
import { useEffect } from 'react'
import { useOvermind } from '../overmind'

const App = () => {
  const { state } = useOvermind()

  useEffect(() => {
    document.querySelector('#app').scrollTop = 0
  }, [state.currentPage])

  return <div />
}

export default App
```

{% endtab %}

{% tab title="Typescript" %}

```javascript
// components/App.tsx
import * as React from 'react'
import { useEffect } from 'react'
import { useOvermind } from '../overmind'

const App: React.FunctionComponent = () => {
  const { state } = useOvermind()

  useEffect(() => {
    document.querySelector('#app').scrollTop = 0
  }, [state.currentPage])

  return <div />
}

export default App
```

{% endtab %}
{% endtabs %}

Here you can also use the traditional approach of subscribing to updates.

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

```typescript
// components/App.jsx
import * as React from 'react'
import { useEffect } from 'react'
import { useOvermind } from '../overmind'

const Todos = () => {
  const { reaction } = useOvermind()

  useEffect(() => {
    return reaction(
      ({ currentPage }) => currentPage,
      () => document.querySelector('#app').scrollTop = 0
    })
  }, [])

  return <div />
}

export default Todos
```

{% endtab %}

{% tab title="Typescript" %}

```javascript
// components/App.tsx
import * as React from 'react'
import { useEffect } from 'react'
import { useOvermind } from '../overmind'

const Todos: React.FunctionComponent = () => {
  const { reaction } = useOvermind()

  useEffect(() => {
    return reaction(
      ({ currentPage }) => currentPage,
      () => document.querySelector('#app').scrollTop = 0
    })
  }, [])

  return <div />
}

export default Todos
```

{% endtab %}
{% endtabs %}

## Higher Order Component

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

```typescript
// overmind/index.js
import { createConnect } from 'overmind-react'
import { state } from './state'
import * as actions from './actions'

export const config = {
  state,
  actions
}

export const connect = createConnect()

// index.jsx
import * as React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import App from './components/App'

const overmind = createOvermind(config)

render((
  <Provider value={overmind}>
    <App />
  </Provider>
), document.querySelector('#app'))

// components/App.jsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

const App = ({ overmind }) => {
  const { state, actions, effects, addMutationListener } = overmind

  return <div />
}

export default connect(App)
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// overmind/index.ts
import { IConfig } from 'overmind'
import { createConnect, IConnect } from 'overmind-react'
import { state } from './state'
import * as actions from './actions'

export const config = {
  state,
  actions
}

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}

export interface Connect extends IConnect<typeof config> {}

export const connect = createConnect<typeof config>()

// index.tsx
import * as React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import App from './components/App'

const overmind = createOvermind(config)

render((
  <Provider value={overmind}>
    <App />
  </Provider>
), document.querySelector('#app'))

// components/App.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

type Props = {} & Connect

const App: React.FunctionComponent<Props> = ({ overmind }) => {
  const { state, actions, effects, addMutationListener } = overmind

  return <div />
}

export default connect(App)
```

{% endtab %}
{% endtabs %}

### Rendering

When you connect a component with the **connect HOC** it will be responsible for tracking and trigger a render when the tracked state is updated. The **overmind** prop passed to the component you defined holds the state and actions. If you want to detect inside your component that it was indeed an Overmind state change causing the render you can compare the **overmind** prop itself.

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

```typescript
// components/App.jsx
import * as React from 'react'
import { connect } from '../overmind'

class App extends React.Component {
  shouldComponentUpdate(nextProps) {
    return this.props.overmind !== nextProps.overmind
  }
  render() {
    return <div />
  }
}

export default connect(App)
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// components/App.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

type Props = {} & Connect

class App extends React.Component<Props> {
  shouldComponentUpdate(nextProps: Props) {
    return this.props.overmind !== nextProps.overmind
  }
  render() {
    return <div />
  }
}

export default connect(App)
```

{% endtab %}
{% endtabs %}

You will not be able to compare a previous state value in Overmind with the new. That is simply because Overmind is not immutable and it should not be. You will not use **shouldComponentUpdate** to compare state in Overmind, though you can of course still use it to compare props from a parent. This is a bit of a mindshift if you come from Redux, but it actually removes the mental burden of doing this stuff.

If you previously used **componentDidUpdate** to trigger an effect, that is no longer necessary either. You rather listen to state changes in Overmind using **addMutationListener** specified below in *effects*.

### Passing state as props

If you pass a state object or array as a property to a child component you will also in the child component need to **connect**. This ensures that the property you passed is tracked within that component, even though you do not access any state or actions from Overmind. The devtools will help you identify where any components are left “unconnected”.

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

```typescript
// components/Todos.jsx
import * as React from 'react'
import { connect } from '../overmind'
import Todo from './Todo'

const Todos = ({ overmind }) => {
  const { state } = overmind

  return (
    <ul>
      {state.todos.map(todo => <Todo key={todo.id} todo={todo} />)}
    </ul<
  )
}

export default connect(Todos)

// components/Todo.tsx
import * as React from 'react'
import { connect } from '../overmind'

const Todo = ({ todo }) => {
  return <li>{todo.title}</li>
}

export default connect(Todo)
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// components/Todos.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'
import Todo from './Todo'

type Props = {} & Connect

const Todos: React.FunctionComponent<Props> = ({ overmind }) => {
  const { state } = overmind

  return (
    <ul>
      {state.todos.map(todo => <Todo key={todo.id} todo={todo} />)}
    </ul<
  )
}

export default connect(Todos)

// components/Todo.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

type Props = {
  todo: Todo
} & Connect

const Todo: React.FunctionComponent<Props> = ({ todo }) => {
  return <li>{todo.title}</li>
}

export default connect(Todo)
```

{% endtab %}
{% endtabs %}

### Reactions

To run reactions in components based on changes to state you use the **reaction** function in the lifecycle hooks of React.

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

```typescript
// components/App.jsx
import * as React from 'react'
import { connect } from '../overmind'

class App extends React.Component {
  private disposeReaction
  componentDidMount() {
    this.disposeReaction = this.props.overmind.reaction(
      (state) => state.currentPage,
      () => document.querySelector('#app').scrollTop = 0
    )
  }
  componentWillUnmount() {
    this.disposeReaction()
  }
  render() {
    const { state, actions } = this.props.overmind

    return <div />
  }
}

export default connect(App)
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
// components/App.tsx
import * as React from 'react'
import { connect, Connect } from '../overmind'

type Props = {} & Connect

class App extends React.Component<Props> {
  disposeReaction: () => void
  componentDidMount() {
    this.disposeReaction = this.props.overmind.reaction(
      (state) => state.currentPage,
      () => document.querySelector('#app').scrollTop = 0
    )
  }
  componentWillUnmount() {
    this.disposeReaction()
  }
  render() {
    const { state, actions } = this.props.overmind

    return <div />
  }
}

export default connect(App)
```

{% endtab %}
{% endtabs %}

## React Native

Overmind supports React Native with **hook** and **Higher Order Component**. What to take notice of though is that native environments sometimes hides the **render** function of React. That can be a bit confusing in terms of setting up the **Provider**. If your environment only exports an initial component, that component needs to be responsible for settings up the providers and rendering your main component:

```typescript
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import MyApp from './MyApp'

const overmind = createOvermind(config)

export function App() {
  return (
    <Provider value={overmind}>
      <MyApp />
    </Provider>
  )
}
```


# Angular

Let us have a look at how you configure your app:

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { Injectable } from '@angular/core'
import { OvermindService } from 'overmind-angular'
import { state } from './state'
import * as actions from './actions'

export const config = { state, actions }

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}

@Injectable({
  providedIn: 'root'
})
export class Store extends OvermindService<typeof config> {}
```

{% endtab %}

{% tab title="app.module.ts" %}

```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { createOvermind } from 'overmind';
import { OvermindModule, OvermindService, OVERMIND_INSTANCE } from 'overmind-angular'

import { config, Store } from './overmind'
import { AppComponent } from './app.component';

@NgModule({
  imports: [ BrowserModule, OvermindModule ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ],
  providers: [
    { provide: OVERMIND_INSTANCE, useFactory: () => createOvermind(config) },
    { provide: Store, useExisting: OvermindService }
]
})
export class AppModule { }

```

{% endtab %}

{% tab title="components/app.component.ts" %}

```typescript
import { Component, ChangeDetectionStrategy } from '@angular/core'
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
<div *track>
  <h1 (click)="actions.changeTitle()">{{ state.title }}</h1>
</div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  state = this.store.select()
  actions = this.store.actions
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="main.ts" %}

```typescript
import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

import { AppModule } from "./app/app.module";
import { environment } from "./environments/environment";

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule, {
    // We do not need zones, we rather use the tracking
    // directive, which gives us a pretty signifcant performance
    // boost. Note that 3rd party libraries might need ngZone,
    // in which case you can not set it to "noop"
    ngZone: "noop"
  })
  .catch(err => console.log(err));

```

{% endtab %}
{% endtabs %}

The **service** is responsible for exposing the configuration of your application. The **\*track** directive is what does the actual tracking. Just put it at the top of your template and whatever state you access will be optimally tracked. You can also select a namespace from your state to expose to the component:

{% tabs %}
{% tab title="components/app.component.ts" %}

```typescript
import { Component, ChangeDetectionStrategy } from '@angular/core'
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
<div *track>
  <h1 (click)="actions.changeAdminTitle()">{{ state.adminTitle }}</h1>
</div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  state = this.store.select(state => state.admin)
  actions = this.store.actions.admin
  constructor(private store: Store) {}
},
```

{% endtab %}
{% endtabs %}

You can now access the **admin** state and actions directly with **state** and **actions**.

### Polyfill environment

Angular does not inject the environment, so in your **polyfill.ts** file you have to add the following:

```typescript
import { environment } from './environments/environment';

(window as any).process = {
  env: {
    NODE_ENV: environment.production ? 'production' : 'development'
  },
};
```

## NgZone

The Overmind **\*track** directive knows when your components should update, and so is much more efficient at change detection than Angular's default NgZone. In order to take advantage of the efficiency provided by the \***track** directive, you *must* set **ngZone** to "noop". Note that other 3rd party libraries may not support this. If for any reason you can't set **ngZone** to "noop", then the \***track** directive is redundant, and you can safely exclude it from your templates.

## Rendering

When you connect Overmind to your component and expose state you do not have to think about how much state you expose. The exact state that is being accessed in the template is the state that will be tracked. That means you can expose all the state of the application to all your components without worrying about performance.

## Passing state as input

When you pass state objects or arrays as input to a child component that state will by default be tracked on the component passing it along, which you can also see in the devtools. By just adding the **\*tracker** directive to the child template, the tracking will be handed over:

{% tabs %}
{% tab title="components/todo.component.ts" %}

```typescript
import { Component, Input, ChangeDetectionStrategy } from '@angular/core'
import { Todo } from '../overmind/state'

@Component({
  selector: 'todos-todo',
  template: `
<li *track>{{ todo.title }}</li>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TodoComponent {
  @Input() todo: Todo
}
```

{% endtab %}

{% tab title="components/todos.component.ts" %}

```typescript
import { Component, ChangeDetectionStrategy } from '@angular/core'
import { Store } from '../overmind'

@Component({
  selector: 'todos-list',
  template: `
<ul *track>
  <todos-todo *ngFor="let todo of state.todos;" [todo]="todo"></todos-todo>
</ul>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ListComponent {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endtab %}
{% endtabs %}

What is important to understand here is that Overmind is **not** immutable. That means if you would change any property on any todo, only the component actually looking at the todo will render. The list is untouched.

## Reactions

To run effects in components based on changes to state you use the **reaction** function in the lifecycle hooks of Angular.

{% tabs %}
{% tab title="components/app.component.ts" %}

```typescript
import { Component } from '@angular/core'
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  disposeReaction: () => void
  constructor (private store: Store) {}
  ngOnInit() {
    this.disposeReaction = this.store.reaction(
      ({ currentPage }) => currentPage,
      () => document.querySelector('#app').scrollTop = 0
    )
  }
  ngOnDestroy() {
    this.disposeReaction()
  }
}
```

{% endtab %}
{% endtabs %}


# Vue

There are two approaches to connecting Overmind to Vue.

## Plugin

Vue has a plugin system that allows us to expose Overmind to all components. This allows minimum configuration and you just use state etc. from any component.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { createPlugin } from 'overmind-vue'

const overmind = createOvermind({
  state: {
    foo: 'bar'
  },
  actions: {
    onClick() {}
  }
})

export const OvermindPlugin = createPlugin(overmind)
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import Vue from 'vue/dist/vue'
import { OvermindPlugin } from './overmind'

Vue.use(OvermindPlugin)

...
```

{% endtab %}

{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="actions.onClick">
    {{ state.foo }}
  </div>
</template>
```

{% endtab %}
{% endtabs %}

If you rather want to expose state, actions and effects differently you can configure that.

{% tabs %}
{% tab title="index.js" %}

```typescript
import Vue from 'vue/dist/vue'
import { OvermindPlugin } from './overmind'

Vue.use(OvermindPlugin, ({ state, actions, effects }) => ({
  admin: state.admin,
  posts: state.posts,
  actions,
  effects
}))

...
```

{% endtab %}

{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="actions.onClick">
    {{ admin.foo }} {{ posts.foo }}
  </div>
</template>
```

{% endtab %}
{% endtabs %}

### Rendering

Any state accessed in the component will cause the component to render when a mutation occurs on that state. Overmind actually uses the same approach to change detection as Vue itself. When using the plugin any component can access any state, though the only overhead that is added to the application is an instance of a “tracking tree” per component. This might sound scary, but it is a tiny little object that adds a callback function to Overmind as long as the component lives. These tracking trees are even reused as components unmount.

### Pass state as props

If you pass anything from the state to a child component it will just work out of the box. The child component will “rescope” the property to its own tracking tree. This ensures that the property you passed is tracked within that component.

{% tabs %}
{% tab title="components/Todo.vue" %}

```typescript
<template>
  <li>{{ todo.title }}</li>
</template>
<script>
export default {
  name: 'Todo',
  props: ["todo"]
}
</script>
```

{% endtab %}

{% tab title="components/Todos.vue" %}

```typescript
<template>
  <ul>
    <todo-component
      v-for="post in state.postsList"
      :todo="todo"
      :key="todo.id"
    ></todo-component>
  </ul>
</template>
<script>
import TodoComponent from './Todo'

export default {
  name: 'Todo',
  components: {
    TodoComponent
  }
}
</script>
```

{% endtab %}
{% endtabs %}

### Reactions

To run effects in components based on changes to state you use the **reaction** function in the lifecycle hooks of Vue.

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="overmind.actions.onClick">
    {{ overmind.state.foo }}
  </div>
</template>
<script>
import { connect } from '../overmind'

export default connect({
  mounted() {
    this.disposeReaction = this.overmind.reaction(
      ({ currentPage }) => currentPage,
      () => document.querySelector('#app').scrollTop = 0
    )
  },
  destroyed() {
    this.disposeReaction()
  }
})
</script>
```

{% endtab %}
{% endtabs %}

## Connect

If you want more manual control of what components connect to Overmind you can use the connector.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { createConnect } from 'overmind-vue'

const overmind = createOvermind({
  state: {},
  actions: {}
})

export const connect = createConnect(overmind)
```

{% endtab %}

{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="overmind.actions.onClick">
    {{ overmind.state.foo }}
  </div>
</template>
<script>
import { connect } from '../overmind'

const Component = {}

export default connect(Component)
</script>
```

{% endtab %}
{% endtabs %}

You can also expose parts of the configuration on custom properties of the component:

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div @click="actions.someAdminAction">
    {{ state.someAdminState }}
  </div>
</template>
<script>
import { connect } from '../overmind'

const Component = {}

export default connect(({ state, actions, effects }) => ({
  state: state.admin,
  actions: actions.admin
}), Component)
</script>
```

{% endtab %}
{% endtabs %}

You can now access the **admin** state and actions directly with **state** and **actions**.

## Computed

Vue has its own observable concept that differs from Overmind. That means you can not use Overmind state inside a computed and expect the computed cache to be busted when the Overmind state changes. But computeds are really for caching expensive computation, which you will rather do inside Overmind using **derived** anyways.

## Using props

You can combine Overmind state with props to dynamically extract state.

{% tabs %}
{% tab title="components/SomeComponent.vue" %}

```typescript
<template>
  <div>
    {{ title }}
  </div>
</template>
<script>
export default {
  name: 'SomeComponent',
  props: ["id"],
  data: (self) => ({
    get title() {
      return self.state.titles[self.id]
    }
  })
}
</script>
```

{% endtab %}
{% endtabs %}


# GraphQL

Using Graphql with Overmind gives you the following benefits:

* **Query:** The query for data is run with the rest of your application logic, unrelated to mounting components
* **Cache:** You integrate the data from Graphql with your existing state, allowing you to control when new data is needed
* **Optimistic updates:** With the data integrated with your Overmind state you can also optimistically update that state before running a mutation query

## Get up and running

Install the separate package:

```
npm install overmind-graphql
```

### Initial state

The Graphql package is an *effect*. Though since we are operating on state, let us prepare some:

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="overmind/state.js" %}

```typescript
export const state = {
  posts: []
}
```

{% endtab %}
{% endtabs %}

### The effect

Now let us introduce the effect:

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'
import { onInitialize } from './onInitialize'
import { gql } from './effects/gql'

export const config = {
  onInitialize,
  state,
  effects: {
    gql
  }
}
```

{% endtab %}

{% tab title="overmind/onInitialize.js" %}

```javascript
export const onInitialize = ({ effects }) => {
  effects.gql.initialize({
    // query and mutation options
    endpoint: 'http://some-endpoint.dev',
  }, {
    // subscription options
    endpoint: 'ws://some-endpoint.dev',  
  })
}
```

{% endtab %}

{% tab title="overmind/effects/gql/index.js" %}

```javascript
import { graphql } from 'overmind-graphql'
import * as queries from './queries'
import * as mutations from './mutations'
import * as subscriptions from './subscriptions'

export const gql = graphql({
  queries,
  mutations,
  subscriptions
})
```

{% endtab %}

{% tab title="overmind/effects/gql/queries.js" %}

```typescript
import { gql } from 'overmind-graphql'

export const posts = gql`
  query Posts {
    posts {
      id
      title
    }
  }
`;
```

{% endtab %}

{% tab title="overmind/effects/gql/mutations.js" %}

```typescript
import { gql } from 'overmind-graphql'

export const createPost = gql`
  mutation CreatePost($title: String!) {
    createPost(title: $title) {
      id
    }
  }
`
```

{% endtab %}

{% tab title="overmind/effects/gql/subscriptions.js" %}

```javascript
import { gql } from 'overmind-graphql'

export const onPostAdded = gql`
  subscription PostAdded() {
    postAdded() {
      id
      title
    }
  }
`
```

{% endtab %}
{% endtabs %}

You define **queries,** **mutations** and **subscriptions** with the effect. That means you can have multiple effects holding different queries and even endpoints. The endpoints are defined when you initialize the effect. This allows you to dynamically create the endpoints based on state, and also pass state related to requests to the endpoints. The queries, mutations and subscriptions are converted into Overmind effects that you can call from your actions.

## Query

To call a query you will typically use an action. Let us create an action that uses our **posts** query.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPosts = async ({ state, effects }) => {
  const { posts } = await effects.gql.queries.posts()

  state.posts = posts
}
```

{% endtab %}
{% endtabs %}

## Mutate

Mutation queries are basically the same as normal queries. You would typically also call these from an action.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPosts = async ({ state, effects }) => {
  const { posts } = await effects.gql.queries.posts()

  state.posts = posts
}

export const addPost = async ({ effects }, title) => {
  await effects.gql.mutations.createPost({ title })
}
```

{% endtab %}
{% endtabs %}

## Subscription

Subscriptions are also available via actions. You typically give them an action which triggers whenever the subscription triggers.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPosts = async ({ state, effects, actions }) => {
  const { posts } = await effects.gql.queries.posts()

  state.posts = posts

  effects.gql.subscriptions.onPostAdded(actions.onPostAdded)
}

export const addPost = async ({ effects }, title) => {
  await effects.gql.mutations.createPost({ title })
}

export const onPostAdded = ({ state }, post) => {
  state.posts.push(post)
}
```

{% endtab %}
{% endtabs %}

## Cache

Now that we have the data from our query in the state, we can decide ourselves when we want this data to update. It could be related to moving back to a certain page, maybe you want to update the data in the background or maybe it is enough to just grab it once. You do not really think about it any differently here than with any other data fetching solution.

## Optimistic updates

Again, since our data is just part of our state we are in complete control of optimistically adding new data. Let us create an optimistic post.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPosts = async ({ state, effects }) => {
  const { posts } = await effects.queries.posts()

  state.posts = posts
}

export const addPost = async ({ state, effects }, title) => {
  const optimisticId = String(Date.now())

  state.posts.push({
    id: optimisticId,
    title
  })

  const { id } = await effects.mutations.createPost({ title })
  const optimisticPost = state.posts.find(post => post.id === optimisticId)

  optimisticPost.id = id
}
```

{% endtab %}
{% endtabs %}

## Options

There are two points of options in the Graphql factory. The **headers** and the **options**.

The headers option is a function which receives the state of the application. That means you can produce request headers dynamically. This can be useful related to authentciation.

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = ({ state, effects }) => {
  effects.gql.initialize({
    endpoint: 'http://some-endpoint.dev',
    // This runs on every request
    headers: () => ({
      authorization: `Bearer ${state.auth.token}`
    }),
    // The options are the options passed to GRAPHQL-REQUEST
    options: {
      credentials: 'include',
      mode: 'cors',
    },
  }, {
    endpoint: 'ws://some-endpoint.dev',
    // This runs on every connect
    params: () => ({
      token: state.auth.token
    })
  })
}
```

{% endtab %}
{% endtabs %}

## Custom subscription socket

If you want to define your own socket for connecting to subscriptions, a function can be used instead:

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```javascript
export const onInitialize = ({ effects }) => {
  effects.gql.initialize(
    {
      endpoint: 'http://some-endpoint.dev',
    }, 
    () => new Websocket('ws://some-other-endpoint.dev')
  )
}
```

{% endtab %}
{% endtabs %}

## Disposing subscriptions

You can dispose any subscriptions in any action. There are two ways to dispose:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const disposeSubscriptions = async ({ state, effects }) => {
  // Disposes all subscriptions on "onPostAdded"
  effects.gql.subscriptions.onPostAdded.dispose()
  // If the subscription takes a payload, you can dispose specific
  // subscriptions
  effects.gql.subscriptions.onPostChange.disposeWhere(
    data => data.id === state.currentPostId
  )
}
```

{% endtab %}
{% endtabs %}

## Typescript

There is only a single type exposed by the library, **Query**. It is used for queries, mutations and subscriptions.

{% tabs %}
{% tab title="overmind/queries.ts" %}

```typescript
import { Query, gql } from 'overmind-graphql'
// You will understand this very soon
import { Posts } from './graphql-types'

export const posts: Query<Posts> = gql`
  query Posts {
    posts {
      id
      title
    }
  }
`;
```

{% endtab %}
{% endtabs %}

The first **Query** argument is the result of the query. There is also a second query argument which is the payload to the query, as seen here.

{% tabs %}
{% tab title="overmind/mutations.ts" %}

```typescript
import { Query, gql } from 'overmind-graphql'
// You will understand this very soon
import { CreatePost, CreatePostVariables } from './graphql-types'

export const createPost: Query<CreatePost, CreatePostVariables> = gql`
  mutation CreatePost($title: String!) {
    createPost(title: $title) {
      id
    }
  }
`
```

{% endtab %}
{% endtabs %}

### Generate typings

It is possible to generate all the typings for the queries and mutations. This is done by using the [APOLLO](https://www.apollographql.com/) project CLI. Install it with:

```
npm install apollo --save-dev
```

Now you can create a script in your **package.json** file that looks something like:

```typescript
{
  "scripts": {
    "schema": "apollo schema:download --header='X-Hasura-Admin-Secret: password' --endpoint=http://some-endpoint.dev graphql-schema.json && apollo codegen:generate --localSchemaFile=graphql-schema.json --target=typescript --includes=src/overmind/**/*.ts --tagName=gql --no-addTypename --globalTypesFile=src/overmind/graphql-global-types.ts graphql-types"
  }
}
```

To update your types, simply run:

```
npm run schema
```

Apollo will look for queries defined with the **gql** template tag and automatically produce the typings. That means whenever you add, remove or update a query in your code you should run this script to update the typings. It also produces what is called **graphql-global-types**. These are types related to fields on your queries, which can be used in your state definition and/or actions.

{% hint style="info" %}
Note that initially you have to define your queries without types and after running the script you can start typing them to get typing in your app and ensure that your app does not break when you change the queries either in the client or on the server
{% endhint %}

## Optimize query

It is possible to transpile the queries from strings into code. This reduces the size of your bundle, though only noticeably if you have a lot of queries. This can be done with the [BABEL-PLUGIN-GRAPHQL-TAG](https://github.com/gajus/babel-plugin-graphql-tag).


# Connecting components

Now that you have defined a state describing your application, you probably want to transform that state into a user interface. There are many ways to express this and Overmind supports the most popular libraries and frameworks for doing this transformation, typically called a view layer. You can also implement a custom view layer if you want to.

By installing the view layer of choice you will be able to connect it to your Overmind instance, exposing its state, actions and effects.

{% tabs %}
{% tab title="React" %}
{% code title="App.jsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../../overmind'

const App = () => {
  const { state } = useOvermind()

  if (state.isLoading) {
    return <div>Loading app...</div>
  }

  return <h1>My awesome app</h1>
}

export default App
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="app.component.ts" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
<div *track>
  <div *ngIf="state.isLoading">
    Loading app...
  </div>
  <h1 *ngIf="!state.isLoading">
    My awesome app
  </h1>
</div>
  `
})
export class App {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <div v-if="state.isLoading">
    Loading app...
  </div>
  <h1 v-else>My awesome app</h1>
</template>
```

{% endtab %}
{% endtabs %}

In this example we are accessing the **isLoading** state. When this component renders and this state is accessed, Overmind will automatically understand that this component is interested in this exact state. It means that whenever the value is changed, this component will render again.

## State

When Overmind detects that the **App** component is interested in our **isLoading** state, it is not looking at the value itself, it is looking at the path. The component is pointed to **state.isLoading** which means that when a mutation occurs on that path in the state, the component will render again. Since the value is a boolean value this can only happen when **isLoading** is replaced or removed. The same goes for strings and numbers as well. We do not say that we mutate a string, boolean or a number. We mutate the object or array that holds those values.

The story is a bit different if the state value is an object or an array. These values can not only be replaced and removed, they can also mutate themselves. An object can have keys added or removed. An array can have items added, removed and even change the order of items. Overmind knows this and will notify components respectively. Let us look at how Overmind treats the following scenarios to get a better understanding.

### Arrays

When we just access an array in a component it will re-render if the array itself is replaced, removed or we do a mutation to it. That would mean we push a new item to it, we splice it or sort it.

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const List = () => {
  const { state } = useOvermind()

  return (
    <h1>{state.items}</h1>
  )
}

export default List
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-list',
  template: `
  <h1 *track>{{state.items}}</h1>
  `
})
export class List {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <h1>{{ state.items }}</h1>
</template>
```

{% endtab %}
{% endtabs %}

But what happens if we iterate the array and access a property on each item?

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const List = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.items.map(item => 
        <li key={item.id}>{item.title}</li>
      )}
    </ul>
  )
}

export default App
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-list',
  template: `
  <ul>
    <li *ngFor="let item of state.items;trackby: trackById">
      {{item.title}}
    </li>
  </ul>
  `
})
export class List {
  state = this.store.select()
  constructor(private store: Store) {}
  trackById(index, item) {
    return item.id
  }
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <ul>
    <li v-for="item in state.items" :key="item.id">
      {{ item.title }}
    </li>
  </ul>
</template>
```

{% endtab %}
{% endtabs %}

The benefit now is that the **List** component will only render when there is a change to the actual list, while each individual **Item** component will render when its respective title changes.

### Objects

Objects are similar to arrays. If you access an object you track if that object is replaced or removed. As with arrays, you can mutate the object itself. When you add, replace or remove a key from the object, it is considered a mutation of the object. It means that if you just access the object, the component will render if any keys are added, replaced or removed.

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const List = () => {
  const { state } = useOvermind()

  return (
    <h1>{state.items}</h1>
  )
}

export default List
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-list',
  template: `
  <h1>{{state.items}}</h1>
  `
})
export class List {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <h1>{{ state.items }}</h1>
</template>
```

{% endtab %}
{% endtabs %}

And just like an array you can iterate the object keys to pass items to a child component for optimal rendering.

{% tabs %}
{% tab title="React" %}
{% code title="Item.jsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const Item = ({ item }) => {
  useOvermind()

  return (
    <li>{item.title}</li>
  )
}

export default Item
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="item.component.ts" %}

```typescript
import { Component Input } from '@angular/core';
import { Item } from '../overmind/state'

@Component({
  selector: 'app-list-item',
  template: `
  <li *track>
    {{item.title}}
  </li>
  `
})
export class List {
  @Input() item: Item;
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="Item.vue" %}

```typescript
<template>
  {{ item.title }}
</template>
<script>
export default {
  name: 'Item',
  props: ['item']
}
</script>
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="React" %}
{% code title="List.jsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'
import Item from './Item'

const List = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {Object.keys(state.items).map(key => 
        <Item key={key} item={state.items[key]} />
      )}
    </ul>
  )
}

export default List
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="list.component.ts" %}

```typescript
import { Component Input } from '@angular/core';
import { Item } from '../overmind/state'

@Component({
  selector: 'app-list-item',
  template: `
  <li *track>
    {{item.title}}
  </li>
  `
})
export class List {
  @Input() item: Item;
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="List.vue" %}

```typescript
<template>
  <ul>
    <li is="Item" v-for="item in state.items" :item="item" :key="item.id" />
  </ul>
</template>
<script>
import Item from './Item'

export default {
  name: 'List',
  components: {
    Item,
  },
}
</script>
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Actions

All the actions defined in the Overmind application are available to connected components.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const toggleAwesomeApp = ({ state }) =>
  state.isAwesome = !state.isAwesome
```

{% endtab %}
{% endtabs %}

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const App = () => {
  const { actions } = useOvermind()

  return (
    <button onClick={actions.toggleAwesomeApp}>
      Toggle awesome
    </button>
  )
}

export default App
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
  <button (click)="actions.toggleAwesomeApp()">
    Toggle awesome
  </button>
  `
})
export class App {
  actions = this.store.actions
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <button @click="actions.toggleAwesomeApp()">
    Toggle awesome
  </button>
</template>
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
If you need to pass multiple values to an action, you should rather use an **object** instead.
{% endhint %}

## Reactions

Sometimes you want to make something happen inside a component related to a state change. This is typically doing some manual work on the DOM. When you connect a component to Overmind it also gets access to **reaction**. This function allows you to subscribe to changes in state, mutations as we call them.&#x20;

This example shows how you can scroll to the top of the page every time you change the current article of the app.

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

```typescript
import * as React from 'react'
import { useOvermind } from '../../overmind'

const Article = () => {
  const { reaction } = useOvermind()

  React.useEffect(() => reaction(
    (state) => state.currentArticle,
    () => document.querySelector('#app').scrollTop = 0 
  ), [])

  return <article />
}

export default Article
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
  <article></article>
  `
})
export class App {
  disposeEffect: () => void
  constructor(private store: Store) {}
  ngOnInit() {
    this.disposeReaction = this.store.reaction(
      (state) => state.currentArticle,
      () => document.querySelector('#app').scrollTop = 0   
    )
  }
  ngOnDestroy() {
    this.disposeReaction()
  }
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <article></article>
</template>
<script>
export default {
  name: 'Article',
  mounted() {
    this.disposeReaction = this.overmind.reaction(
      (state) => state.currentArticle,
      () => document.querySelector('#app').scrollTop = 0   
    })
  }
  destroyed() {
    this.disposeReaction()
  }
}
</script>
```

{% endtab %}
{% endtabs %}

## Effects

Any effects you define in your Overmind application are also exposed to the components. They can be found on the property **effects**. It is encouraged that you keep your logic inside actions, but you might be in a situation where you want some other relationship between components and Overmind. A shared effect is the way to go.


# Managing lists

Why do we even have a guide to managing lists? Well, lists are a type of state that differ from other types of state. Both from the perspective of the state itself, but also transforming that state into UI.

{% hint style="info" %}
The discussion of lists is not specific to Overmind and there are no limitations on how you want to approach this. This guide is rather to help you think about how you structure entities (data with an id) to optimally access and render them.
{% endhint %}

## Defining the state

When we want to render a list of something we want an **array**. This is the data structure we instinctively go to as it basically is a list. But arrays are rarely the way you want to store the actual data of the list.

If your list consists of posts, these posts are most likely entities from the server which are unique, and have a unique id. A data structure that better manages uniqueness is an **object**.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/guide/managinglists/object.ts)

```typescript
{
  "uniqueId1": {},
  "uniqueId2": {},
  "uniqueId3": {}
}
```

Another benefit from using an object is that you have a direct reference to the entity by using its id. No need to iterate an array to find what you are looking for. So this is a good rule of thumb: if the state you are defining has unique identifiers they should most likely be stored as an object, not an array.

But we still want to use an array when we transform the state into a UI. Let us see what we can do about that.

## Derive to a list

In Overmind it is encouraged that you derive these dictionaries of entities to a list by deriving the state. The most simple way to do this is:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  posts: {}
  postsList: state => Object.values(state.posts)
}
```

{% endtab %}
{% endtabs %}

Now when we point to **state.postsList** we get an array of posts. What is important to remember here is that we do not create the list again whenever we point to this state value. It is only run again if there is a change to the referenced posts’ state.

## Sorting

Now we have optimally stored our posts in a dictionary for easy access by id. We have also created a derived state which converts this dictionary to an array whenever the source dictionary changes. Though most likely you want to sort the list. Typically lists are sorted chronologically and our posts item has a **datetime** field.

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  posts: {}
  postsList: state =>
    Object.values(state.posts)
      .sort((postA, postB) => {
        if (postA.datetime > postB.datetime) {
          return 1
        } else if (postA.datetime < postB.datetime) {
          return -1
        }

        return 0
      })
}
```

{% endtab %}
{% endtabs %}

There we go, our posts are now shown chronologically. But maybe we only want to show some of the posts that are available? Maybe the list should only contain the ten latest entries?

## Filtering

To limit the number of posts shown we can create a new state and use it inside our derived state to limit the number of results.

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { Derive } from 'overmind'

export type Post {
  id: string
  title: string
  body: string
  datetime: number
}

export type State = {
  posts: { [id: string] : Post }
  showCount: number
  postsList: Derive<State, Post[]>
}

export const state: State = {
  posts: {},
  showCount: 10,
  postsList: state =>
    Object.values(state.posts)
      .sort((postA, postB) => {
        if (postA.datetime > postB.datetime) {
          return 1
        } else if (postA.datetime < postB.datetime) {
          return -1
        }

        return 0
      })
      .slice(0, state.showCount)
}
```

{% endtab %}
{% endtabs %}

Now if we change the **showCount** state our derived list will indeed update.

## Rendering lists

So now let’s look at how we would consume such a list. Let us look at a straightforward example first:

{% tabs %}
{% tab title="React" %}
{% code title="components/App.tsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const Posts: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.postsList.map(post => 
        <li key={post.id}>{post.title}</li>
      )}
    </ul>
  )
}

export default App
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="components/posts.component.ts" %}

```typescript
import { Component } from '@angular/core';
import { connect } from '../overmind'

@Component({
  selector: 'app-posts',
  template: `
  <ul>
    <li *ngFor="let post of overmind.state.postsList;trackby: trackById">
      {{post.title}}
    </li>
  </ul>
  `
})
@connect()
export class List {
  trackById(index, post) {
    return post.id
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="components/Posts.vue" %}

```typescript
<template>
  <ul>
    <li v-for="post in state.postsList" :key="post.id>
      {{ post.title }}
    </li>
  </ul>
</template>
```

{% endcode %}
{% endtab %}
{% endtabs %}

Now this approach will work perfectly fine. The component will render the list and update it whenever it needs to. The only drawback with this approach is that any change to individual posts will also cause the component to render, specifically the **title** of a post since that is the only thing we are looking at. This is because this one component is looking at all the posts. We can optimize this by passing each post down to a child component:

{% tabs %}
{% tab title="React" %}
{% code title="components/Post.tsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'
import { Post as TPost } from '../overmind/state'

type Props = {
  post: TPost
}

const Post: React.FunctionComponent<Props> = ({ post }) => {
  // We still need to use the hook so that the component tracks
  // changes to the post
  useOvermind()

  return (
    <li>{post.title}</li>
  )
}

export default Post
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="components/post.component.ts" %}

```typescript
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
import { Post } from '../overmind/state'

@Component({
  selector: 'app-post',
  template: `
  <li *track>
    {{post.title}}
  </li>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class List {
  @Input() post: Post;
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="components/Post.vue" %}

```typescript
<template>
  <li>{{ post.title }}</li>
</template>
<script>
export {
  props: ['post']
}
</script>
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="React" %}
{% code title="components/Posts.tsx" %}

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'
import Post from './Post'

const Posts: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <ul>
      {state.postsList.map(post => 
        <Post key={post.id} post={post} />
      )}
    </ul>
  )
}

export default Posts
```

{% endcode %}
{% endtab %}

{% tab title="Angular" %}
{% code title="components/posts.component.ts" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-posts',
  template: `
  <ul>
    <app-post
      *ngFor="let post of state.postsList;trackby: trackById"
      [post]="post"
    ></app-post>
  </ul>
  `
})
export class List {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endcode %}
{% endtab %}

{% tab title="Vue" %}
{% code title="components/Posts.vue" %}

```typescript
<template>
  <ul>
    <post-component v-for="post in state.postsList" :post="post" :key="post.id"></post-component>
  </ul>
</template>
<script>
import PostComponent from './Post'

export default {
  name: 'Posts',
  components: {
    PostComponent,
  },
}
</script>
```

{% endcode %}
{% endtab %}
{% endtabs %}

Now the **Posts** component only cares about changes to the list itself, while each **Post** component cares about its corresponding post title. It means that if the title of a post updates, only the component that actually cares about that post renders again. If the list itself changes only the **Posts** component will render.

### Summary <a href="#managing-lists-summary" id="managing-lists-summary"></a>

Managing lists has two considerations: defining how to store the data of the list, and how to actually render the list. It can be a good idea to store data entities with unique ids as a dictionary and rather use a **derived** state to produce the array itself. This gives you best of both worlds – easy lookup using the id, and a cached list that only updates when dependent state updates.


# State first routing

With Overmind you can use whatever routing solution your selected view layer provides. This will most likely intertwine routing state with your component state, which is something Overmind would discourage, but you know… whatever you feel productive in, you should use :-) In this guide we will look into how you can separate your router from your components and make it part of your application state instead. This is more in the spirit of Overmind and throughout this guide you will find benefits of doing it this way.

We are going to use [PAGE.JS](https://www.npmjs.com/package/page) as the router and we will look at a complex routing example where we open a page with a link to a list of users. When you click on a user in the list we will show that user in a modal with the URL updating to the id of the user. In addition we will present a query parameter that reflects the current tab inside the modal.

We will start with a simple naïve approach and then tweak our approach a little bit for the optimal solution.

## Set up the app

Before we go into the router we want to set up the application. We have some state helping us express the UI explained above. In addition we have three actions.

1. **showHomePage** tells our application to set the current page to *home*
2. **showUsersPage** tells our application to set the current page to *users* and fetches the users as well
3. **showUserModal** tells our application to show the modal by setting an id of a user passed to the action. This action will also handle the switching of tabs later.

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
import { Action, AsyncAction } from 'overmind'

export const showHomePage: Action = ({ state }) => {
  state.currentPage = 'home'
}

export const showUsersPage: AsyncAction = async ({ state, effects }) => {
  state.modalUser = null
  state.currentPage = 'users'
  state.isLoadingUsers = true
  state.users = await effects.api.getUsers()
  state.isLoadingUsers = false
}

export const showUserModal: AsyncAction<{ id: string }> = async ({ state, effects }, params) => {
  state.isLoadingUserDetails = true
  state.modalUser = await effects.api.getUserWithDetails(params.id)
  state.isLoadingUserDetails = false
}
```

{% endtab %}
{% endtabs %}

## Initialize the router

**Page.js** is pretty straightforward. We basically want to map a URL to trigger an action. To get started, let us first add Page.js as an effect and take the opportunity to create a custom API. When a URL triggers we want to pass the params of the route to the action linked to the route:

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import page from 'page'

// We allow void type which is used to define "no params"
type IParams = {
  [param: string]: string  
} | void

export const router = {
  initialize(routes: { [url: string]: (params: IParams) => void }) {
    Object.keys(routes).forEach(url => {
      page(url, ({ params }) => routes[url](params))
    })
    page.start()
  },
  open: (url: string) => page.show(url)
}
```

{% endtab %}
{% endtabs %}

Now we can use Overmind’s **onInitialize** to configure the router. That way the initial URL triggers before the UI renders and we get to set our initial state.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

const onInitialize: OnInitialize = ({ actions, effects }) => {
  effects.router.initialize({
    '/': actions.showHomePage,
    '/users': actions.showUsersPage,
    '/users/:id', actions.showUserModal
  })
}

export default onInitialize
```

{% endtab %}
{% endtabs %}

Take notice here that we are actually passing in the params from the router, meaning that the id of the user will be passed to the action.

## The list of users

When we now go to the list of users the list loads up and is displayed. When we click on a user the URL changes, our **showUser** action runs and indeed, we see a user modal.

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

```typescript
// components/App.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'
import Users from './Users'

const App: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <div className="container">
      <nav>
        <a href="/">Home</a>
        <a href="/users">Users</a>
      </nav>
      {state.currentPage === 'home' ? <h1>Hello world!</h1> : null}
      {state.currentPage === 'users' ? <Users /> : null}
    </div>
  )
}

export default App

// components/Users.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'
import UserModal from './UserModal'

const Users: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <div className="content">
      {state.isLoadingUsers ? (
        <h4>Loading users...</h4>
      ) : (
        <ul>
          {state.users.map(user => (
            <li key={user.id}>
              <a href={"/users/" + user.id}>{user.name}</a>
            </li>
          ))}
        </ul>
      )}
      {state.isLoadingUserDetails || state.modalUser ? <UserModal /> : null}
    </div>
  )
}

export default Users

// components/UserModal.tsx
import * as React from 'react'
import { useOvermind } from '../overmind'

const UserModal: React.FunctionComponent = () => {
  const { state } = useOvermind()

  return (
    <a href="/users" className="backdrop">
      <div className="modal">
        {state.isLoadingUserDetails ? (
          <h4>Loading user details...</h4>
        ) : (
          <>
            <h4>{state.modalUser.name}</h4>
            <h6>{state.modalUser.details.email}</h6>
            <nav>
              <a href={"/users/" + state.modalUser.id + "?tab=0"}>bio</a>
              <a href={"/users/" + state.modalUser.id + "?tab=1"}>address</a>
            </nav>
            {state.currentUserModalTabIndex === 0 ? (
              <div className="tab-content">{state.modalUser.details.bio}</div>
            ) : null}
            {state.currentUserModalTabIndex === 1 ? (
              <div className="tab-content">{state.modalUser.details.address}</div>
            ) : null}
          </>
        )}
      </div>
    </a>
  )
}

export default UserModal
```

{% endtab %}

{% tab title="Angular" %}

```typescript
// components/app.component.ts
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-component',
  template: `
  <div class="container" *track>
    <nav>
      <a href="/">Home</a>
      <a href="/users">Users</a>
    </nav>
    <h1 *ngIf="state.currentPage === 'home'">Hello world!</h1>
    <users-list *ngIf="state.currentPage === 'users'"></users-list>
  </div>
  `
})
export class AppComponent {
  state = this.store.select()
  constructor(private store: Store) {}
}

// components/users-list.component.ts
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'users-list',
  template: `
  <div class="content" *track>
    <h4 *ngIf="state.isLoadingUsers">Loading users...</h4>
    <ul *ngIf="!state.isLoadingUsers">
      <li *ngFor="let user of state.users;trackby: trackById">
        <a href={"/users/" + user.id}>{{user.name}}</a>
      </li>
    </ul>
    <user-modal *ngIf="state.isLoadingUserDetails || state.userModal"></user-modal>
  </div>
  `
})
export class UsersList {
  state = this.store.select()
  constructor(private store: Store) {}
  trackById(index, user) {
    return user.id
  }
}

// components/user-modal.component.ts
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'user-modal',
  template: `
  <a href="/users" class="backdrop">
    <div class="modal">
      <h4 *ngIf="state.isLoadingUserDetails">Loading user details...</h4>
      <div *ngIf="!state.isLoadingUserDetails">
        <h4>{{state.modalUser.name}}</h4>
        <h6>{{state.modalUser.details.email}}</h6>
        <nav>
          <a [href]="'/users/' + state.modalUser.id + '?tab=0'">bio</a>
          <a [href]="'/users/' + state.modalUser.id + '?tab=1'">address</a>
        </nav>
        <div
          *ngIf="state.currentUserModalTabIndex === 0"
          class="tab-content"
        >
          {{modalUser.details.bio}}
        </div>
        <div
          *ngIf="state.currentUserModalTabIndex === 1"
          class="tab-content"
        >
          {{modalUser.details.address}}
        </div>
      </div>
    </div>
  </a>
  `
})
export class UserModal {
  state = this.store.select()
  constructor(private store: Store) {}
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
// components/App.vue
<template>
  <div class="container">
    <nav>
      <a href="/">Home</a>
      <a href="/users">Users</a>
    </nav>
    <h1 v-if="state.currentPage === 'home'">Hello world!</h1>
    <users-list v-if="state.currentPage === 'users'"></users-list>
  </div>
</template>

// components/UsersList.vue
<template>
  <div class="content">
    <h4 v-if="state.isLoadingUsers">Loading users...</h4>
    <ul v-else>
      <li v-for="user in state.users" :key="user.id">
        <a :href="'/users/' + user.id">{{ user.name }}</a>
      </li>
    </ul>
    <user-modal v-if="state.isLoadingUserDetails || state.userModal"></user-modal>
  </div>
</template>

// components/UserModal.vue
<template>
  <a href="/users" class="backdrop">
    <div class="modal">
      <h4 v-if="state.isLoadingUserDetails">Loading user details...</h4>
      <div v-else>
        <h4>{{ state.modalUser.name }}</h4>
        <h6>{{ state.modalUser.details.email }}</h6>
        <nav>
          <a :href="'/users/' + state.modalUser.id + '?tab=0'">bio</a>
          <a :href="'/users/' + state.modalUser.id + '?tab=1'">address</a>
        </nav>
        <div
          v-if="state.currentUserModalTabIndex === 0"
          class="tab-content"
        >
          {{ state.modalUser.details.bio }}
        </div>
        <div
          v-if="state.currentUserModalTabIndex === 1"
          class="tab-content"
        >
          {{ modalUser.details.address }}
        </div>
      </div>
    </div>
  </a>
</template>
```

{% endtab %}
{% endtabs %}

But what if we try to refresh now… we get an error. The router tries to run our user modal, but we are on the front page. The modal does not exist there. We want to make sure that when we open a link to a user modal we also go to the actual user list page.

## Composing actions

A straightforward way to solve this is to simply also change the page in the **showUserModal** action, though we would like the list of users to load in the background as well. The logic of **showUsers** might also be a lot more complex and we do not want to duplicate our code. When these scenarios occur where you want to start calling actions from actions, it indicates you have reached a level of complexity where a functional approach might be better. Let us look at how you would implement this both using a functional approach and a plain imperative one.

### Imperative approach

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
import { Action, AsyncAction } from 'overmind'
import { Page } from './types'

export const showHomePage: Action = ({ state }) => {
  state.currentPage = Page.HOME
}

export const showUsersPage: AsyncAction = async ({ state, effects }) => {
  state.currentPage = Page.USERS
  state.modalUser = null

  if (!Object.keys(state.users).length) {
    state.isLoadingUsers = true
    state.users = await effects.api.getUsers()
    state.isLoadingUsers = false
  }
}

export const showUserModal: AsyncAction<{ id: string }> = async ({ state, actions }, params) => {
  actions.showUsersPage()
  state.isLoadingUserDetails = true
  state.modalUser = await effects.api.getUserWithDetails(params.id)
  state.isLoadingUserDetails = false
}
```

{% endtab %}
{% endtabs %}

Going functional depends on complexity and even though the complexity has indeed increased, we can safely manage it using plain imperative code. Whenever we open a user modal we can simply just call the action that takes care of bringing us to the users page as well.

When running actions from within other actions like this it will be reflected in the devtool.

### Functional approach

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, mutate, filter } from 'overmind'
import { Page } from './types'

export const closeUserModal: <T>() => Operator<T> = () =>
  mutate(function closeUserModal({ state }) {
    state.modalUser = null
  })

export const setPage: <T>(page: Page) => Operator<T> = (page) =>
  mutate(function setPage({ state }) {
    state.currentPage = page
  })

export const shouldLoadUsers: <T>() => Operator<T> = () => 
  filter(function shouldLoadUsers({ state }) {
    return !Boolean(state.users.length)
  })

export const loadUsers: <T>() => Operator<T> = () => 
  mutate(async function loadUsers({ state, effects }) {
    state.isLoadingUsers = true
    state.users = await effects.api.getUsers()
    state.isLoadingUsers = false
  })

export const loadUserWithDetails: () => Operator<{ id: string }> = () => 
  mutate(async function loadUserWithDetails({ state, effects }, params) {
    state.isLoadingUserDetails = true
    state.modalUser = await effects.api.getUserWithDetails(params.id)
    state.isLoadingUserDetails = false
  })
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe } from 'overmind'
import { Page } from './types'
import * as o from './operators'

export const showHomePage: Operator = o.setPage(Page.HOME)

export const showUsersPage: Operator = pipe(
  o.setPage(Page.USERS),
  o.closeUserModal(),
  o.shouldLoadUsers(),
  o.loadUsers()
)

export const showUserModal: Operator<{ id: string }> = pipe(
  o.setPage(Page.USERS),
  o.loadUserWithDetails(),
  o.shouldLoadUsers(),
  o.loadUsers(),
)
```

{% endtab %}
{% endtabs %}

By splitting up all our logic into operators we were able to make our actions completely declarative and at the same time reuse logic across them. The *operators* file gives us maintainable code and the *actions* file gives us readable code.

We could actually make this better though. There is no reason to wait for the user of the modal to load before we load the users list in the background. We can fix this with the **parallel** operator. Now the list of users and the single user load at the same time.

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe, parallel } from 'overmind'
import { Page } from './types'
import * as o from './operators'

export const showHomePage: Operator<void> = o.setPage(Page.HOME)

export const showUsersPage: Operator<void> = pipe(
  o.setPage(Page.USERS),
  o.closeUserModal(),
  o.shouldLoadUsers(),
  o.loadUsers()
)

export const showUserModal: Operator<{ id: string }> = pipe(
  o.setPage(Page.USERS),
  parallel(
    o.loadUserWithDetails(),
    pipe(
      o.shouldLoadUsers(),
      o.loadUsers()
    ),
  )
)
```

{% endtab %}
{% endtabs %}

Now you are starting to see how the operators can be quite useful to compose flow. This flow is also reflected in the development tool of Overmind.

## The tab query param

**Page.js** also allows us to manage query strings, the stuff after the **?** in the url. Page.js does not parse it though, so we introduce a library which does just that, [QUERY-STRING](https://www.npmjs.com/package/query-string). With this we can update our router to also pass in any query params.

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import page from 'page'
import queryString from 'query-string'

type IParams = {
  [param: string]: string  
} | void

export const router = {
  initialize(routes: { [url: string]: (IParams) => void }) {
    Object.keys(routes).forEach(url => {
      page(url, ({ params, querystring }) => {
        const payload = Object.assign({}, params, queryString.parse(querystring))

        routes[url](payload)
      })
    })
    page.start()
  },
  open: (url: string) => page.show(url)
}
```

{% endtab %}
{% endtabs %}

### Imperative approach

We now also handle the received tab parameter and make sure that when we change tabs we do not load the user again. We only want to load the user when there is no existing user or if the user has changed.

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
import { Action, AsyncAction } from 'overmind'
import { Page } from './types'

export const showHomePage: Action = ({ state }) => {
  state.currentPage = Page.HOME
}

export const showUsersPage: AsyncAction = async ({ state, effects }) => {
  state.currentPage = Page.USERS
  state.modalUser = null

  if (!Object.keys(state.users).length) {
    state.isLoadingUsers = true
    state.users = await effects.api.getUsers()
    state.isLoadingUsers = false
  }
}

export const showUserModal: AsyncAction<{ id: string, tab: string }> = async ({ state, actions }, params) => {
  actions.showUsersPage()
  state.currentUserModalTabIndex = Number(params.tab)
  state.isLoadingUserDetails = true
  state.modalUser = await effects.api.getUserWithDetails(params.id)
  state.isLoadingUserDetails = false
}
```

{% endtab %}
{% endtabs %}

### Functional approach

Now we can add an operator which uses this **tab** query to set the current tab and then compose it into the action. We also add an operator to verify if we really should load a new user.

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { Operator, mutate, filter } from 'overmind'
import { Page } from './types'

export const closeUserModal: <T>() => Operator<T> = () =>
  mutate(function closeUserModal({ state }) {
    state.modalUser = null
  })

export const setPage: <T>(page: string) => Operator<T> = (page) =>
  mutate(function setPage({ state }) {
    state.currentPage = page
  })

export const shouldLoadUsers: <T>() => Operator<T> = () => 
  filter(function shouldLoadUsers({ state }) {
    return !Boolean(state.users.length)
  })

export const loadUsers: <T>() => Operator<T> = () => 
  mutate(async function loadUsers({ state, effects }) {
    state.isLoadingUsers = true
    state.users = await effects.api.getUsers()
    state.isLoadingUsers = false
  })

export const loadUserWithDetails: () => Operator<{ id: string }> = () => 
  mutate(async function loadUserWithDetails({ state, effects }, params) {
    state.isLoadingUserDetails = true
    state.modalUser = await effects.api.getUserWithDetails(params.id)
    state.isLoadingUserDetails = false
  })

export const shouldLoadUserWithDetails: <T>() => Operator<{ id: string }, T> = () => 
  filter(function shouldLoadUserWithDetails({ state }, params) {
    return !state.modalUser || state.modalUser.id !== params.id
  })

export const setCurrentUserModalTabIndex: <T>() => Operator<{ tab: string }, T> = () =>
  mutate(function setCurrentUserModalTabIndex({ state }, params) {
    state.currentUserModalTabIndex = Number(params.tab)
  })
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe, parallel } from 'overmind'
import { Page } from './types'
import * as o from './operators'

export const showHomePage: Operator = o.setPage(Page.HOME)

export const showUsersPage: Operator = pipe(
  o.setPage(Page.USERS),
  o.closeUserModal(),
  o.shouldLoadUsers(),
  o.loadUsers()
)

export const showUserModal: Operator<{ id: string, tab: string }> = pipe(
  o.setPage(Page.USERS),
  parallel(
    pipe(
      o.setCurrentUserModalTabIndex(),
      o.shouldLoadUserWithDetails(),
      o.loadUserWithDetails()
    ),
    pipe(
      o.shouldLoadUsers(),
      o.loadUsers()
    )
  )
)
```

{% endtab %}
{% endtabs %}

## Summary

With little effort we were able to build a custom “**application state first**“ router for our application. Like many common tools needed in an application, like talking to the server, localStorage etc., there are often differences in the requirements. And even more often you do not need the full implementation of the tool you are using. By using simple tools you can meet the actual requirements of the application more “head on” and this was an example of that.

We also showed how you can solve this issue with an imperative approach or go functional. In this example functional is probably a bit overkill as there is very little composition required. But if your application needed to use these operators many times in different configurations you would benefit more from it.


# Move to Typescript

You are here, great! This will be worth your time.


# Testing

Testing is a broad subject and everybody has an opinion on it. We can only show you how we think about testing in general and how to effectively write those tests for your Overmind app.&#x20;

The most important tests you can write are those who test how your application works when it is all put together, as close to the user experience as possible, so called E2E tests. Testing solutions like [CYPRESS.IO](https://www.cypress.io/) are a great way to do exactly that. You can read more about Cypress and integration testing with Overmind in [THIS ARTICLE](https://www.cypress.io/blog/2019/02/28/shrink-the-untestable-code-with-app-actions-and-effects/#).

You can also do **unit testing** of actions and effects. This will cover expected changes in state and that your side effects behave in a predictable manner. This is typically more important when you are not using Typescript.

## Structuring the app

When you write tests you will create many instances of a mocked version of Overmind with the configuration you have created. To ensure that this configuration can be used many times we have to separate our configuration from the instantiation of the actual app.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { IConfig } from 'overmind'
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

Now we are free to import our configuration without touching the application instance. Lets go!

## Testing actions

When testing an action you’ll want to verify that changes to state are performed as expected. To give you the best possible testing experience Overmind comes with a mocking tool called **createOvermindMock**. It takes your application configuration and allows you to run actions as if they were run from components.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const getPost = async ({ state, api }, id) {
  state.isLoadingPost = true
  try {
    state.currentPost = await api.getPost(id)
  } catch (error) {
    state.error = error
  }
  state.isLoadingPost = false
}
```

{% endtab %}
{% endtabs %}

You might want to test if a thrown error is handled correctly here. This is an example of how you could do that:

{% tabs %}
{% tab title="overmind/actions.test.js" %}

```typescript
import { createOvermindMock } from 'overmind'
import { config } from './'

describe('Actions', () => {
  describe('getPost', () => {
    test('should get post with passed id', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost(id) {
            return Promise.resolve({
              id
            })
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.state).toEqual({
        isLoadingPost: false,
        currentPost: { id: '1' },
        error: null
      })
    })
    test('should handle errors', async () => {
      const overmind = createOvermindMock(config, {
        api = {
          getPost() {
            throw new Error('test')
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.state.isLoadingPost).toBe(false)
      expect(overmind.state.error.message).toBe('test')
    })
  })
})
```

{% endtab %}
{% endtabs %}

If your actions can result in multiple scenarios a unit test is beneficial. But you will be surprised how straightforward the logic of your actions will become. Since effects are encouraged to be application specific you will most likely be testing those more than you will test any action.

You do not have to explicitly write the expected state. You can also use for example [JEST](https://www.overmindjs.org/guides/intermediate/05_writingtests?view=react\&typescript=true) for snapshot testing. The mock instance has a list of mutations performed. This is perfect for snapshot testing.

{% tabs %}
{% tab title="overmind/actions.test.js" %}

```typescript
import { createOvermindMock } from 'overmind'
import { config } from './'

describe('Actions', () => {
  describe('getPost', () => {
    test('should get post with passed id', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost(id) {
            return Promise.resolve({
              id
            })
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.mutations).toMatchSnapshot()
    })
    test('should handle errors', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost() {
            throw new Error('test')
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.mutations).toMatchSnapshot()
    })
  })
})
```

{% endtab %}
{% endtabs %}

In this scenario we would also ensure that the **isLoadingPost** state indeed flipped to *true* before moving to *false* at the end.

## Testing onInitialize

The **onInitialize** hook will not trigger during testing. To test this action you have to trigger it yourself.

{% tabs %}
{% tab title="overmind/onInitialize.test.js" %}

```typescript
import { createOvermindMock } from 'overmind'
import { config } from './'

describe('Actions', () => {
  describe('onInitialize', () => {
    test('should initialize with local storage theme', async () => {
      const overmind = createOvermindMock(config, {
        localStorage: {
          getTheme() {
            return 'awesome' 
          }
        }
      })

      await overmind.onInitialize()

      expect(overmind.state.theme).toEqual('awesome')
    })
  })
})
```

{% endtab %}
{% endtabs %}

### Testing effects <a href="#writing-tests-testing-effects" id="writing-tests-testing-effects"></a>

Where you want to put in your effort is with the effects. This is where you have your chance to build a domain specific API for your actual application logic. This is the bridge between some generic tool and what your application actually wants to use it for.

A simple example of this is doing requests. Maybe you want to use e.g. [AXIOS](https://github.com/axios/axios) to reach your API, but you do not really care about testing that library. What you want to test is that it is used correctly when you use your application specific API.

This is just an example showing you how you can structure your code for optimal testability. You might prefer a different approach or maybe rely on integration tests for this. No worries, you do what makes most sense for your application:

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
import * as axios from 'axios'

// This is the class we can create new instances of when testing
export class Api {
  constructor(request, options) {
    this.request = request
    this.options = options
  }
  async getPost(id: string) {
    try {
      const response = await this.request.get(this.options.baseUrl + '/posts/' + id, {
        headers: {
          'Auth-Token': this.options.authToken
        }
      })

      return response.data
    } catch (error) {
      throw new Error('Could not grab post with id ' + id)
    }
  }
}

// We export the default instance that we actually use with our
// application
export const api = new Api(axios, {
  authToken: '134981091031hfh31',
  baseUrl: '/api'
})
```

{% endtab %}
{% endtabs %}

Let’s see how you could write a test for it:

{% tabs %}
{% tab title="overmind/effects.test.js" %}

```typescript
import { Api } from './effects'

describe('Effects', () => {
  describe('Api', () => {
    test('should get a post using baseUrl and authToken in header', async () => {
      expect.assertions(3)
      const api = new Api({
        get(url, config) {
          expect(url).toBe('/test/posts/1')
          expect(config).toEqual({
            headers: {
              'Auth-Token': '123'
            }
          })

          return Promise.resolve({
            response: {
              id
            }
          })
        }
      }, {
        authToken: '123',
        baseUrl: '/test'
      })

      const post = await api.getPost('1')

      expect(post.id).toBe('1')
    })
  })
})
```

{% endtab %}
{% endtabs %}

Again, effects are where you typically have your most brittle logic. With the approach just explained you will have a good separation between your application logic and the brittle and “impure”. In an Overmind app, especially written in Typescript, you get very far just testing your effects and then do integration tests for your application. But as mentioned in the introduction we all have very different opinions on this, at least the API allows testing to whatever degree you see fit.


# action

```typescript
import { AsyncAction } from 'overmind'

export const getPosts: AsyncAction = async ({ state, actions, effects }) => {
  state.isLoadingPosts = true
  state.posts = await effects.api.getPosts()
  state.isLoadingPosts = false
}
```

An action is where you write the logic of the application. Every action receives at least one argument and that is the **context**. This is the signature of the context:

`{ state, actions, effects }`

This *injected* context allows Overmind to understand from where you are changing state and running effects. You can also use other actions defined in your application. Additionally with *injection* your actions become highly testable as it can easily be mocked.

State changes are restricted to these actions. That means if you try to change the state outside of an action you will get an error. The state changes are also scoped to the action. That means it does not matter if you perform the state change asynchronously, either by defining the action as an **async** function or for example use a **setTimeout**. You can change the state at any time within the action.

## Payload

When an action is called you can optionally pass it a payload. This payload is received as the second argument to the action.

```typescript
import { Action } from 'overmind'

export const setTitle: Action<string> = ({ state }, title) => {
  state.title = title
}
```

{% hint style="info" %}
There is only one argument, which means if you want to pass multiple values you have to do so with an object
{% endhint %}

## Typing

There are two different action types in Overmind, **Action** and **AsyncAction**. Both of them takes an Input param and an Output param where both of them default to **void**.

`Action<void, void>`

`AsyncAction<void, void>`.

The difference is that **AsyncAction** returns a Promise of the output, **Promise\<void>**. Basically whenever you use an **async** action or explicitly return a promise from an action you should use the **AsyncAction** type.


# addFlushListener

The **addMutationListener** triggers whenever there is a mutation. The **addFlushListener** triggers whenever Overmind tells components to render again. It can have multiple mutations related to it.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

const onInitialize: OnInitialize = async ({ state, effects }, overmind) => {
  overmind.addFlushListener(effects.history.addMutations)
}

export default onInitialize
```

{% endtab %}
{% endtabs %}


# addMutationListener

It is possible to listen to all mutations performed in Overmind. This allows you to create special effects based on mutations within a certain domain of your app, or whatever else you come up with. Note that this method triggers right after any mutation occurs, you might rather want to use **addFlushListener** to be notified about batched changes, like the components does.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

const onInitialize: OnInitialize = async ({ state, localStorage }, overmind) => {
  overmind.addMutationListener((mutation) => {
    if (mutation.path.indexOf('todos') === 0) {
      localStorage.set('todos', state.todos)
    }
  })
}

export default onInitialize
```

{% endtab %}
{% endtabs %}


# createOvermind

The **createOvermind** factory is used to create the application instance. You need to create and export a mechanism to connect your instance to the components. Please look at the guides for each view layer for more information.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { state } from './state'
import * as effects from './effects'
import * as actions from './actions'

export const config = {
  state,
  effects,
  actions
}

// For explicit typing check the Typescript guide
declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}

You can pass a second argument to the **createOvermind** factory. This is an options object with the following properties.

## options.devtools

If you develop your app on localhost the application connects to the devtools on **localhost:3031**. You can change this in case you need to use an IP address, the devtools is configured with a different port or you want to connect to localhost (with default port) even though the app is not on localhost.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/api/app_options_devtools.ts)

```typescript
const overmind = createOvermind(config, {
  devtools: true // 'localhost:3031'
})
```

## options.logProxies

By default, in **development**, Overmind will make sure that any usage of **console.log** will log out the actual object/array, instead of any proxy wrapping it. This is most likely what you want. If you want to turn off this behaviour, set this option to **true**.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/api/app_options_logproxies.ts)

```typescript
const overmind = createOvermind(config, {
  logProxies: false
})
```

## options.name

If you have multiple instances of Overmind on the same page you can name your app to differentiate them.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/api/app_options_name.ts)

```typescript
const overmindA = createOvermind(configA, {
  name: 'appA'
})

const overmindB = createOvermind(configB, {
  name: 'appB'
})
```

## options.hotReloading

By default Overmind will do the necessary hot reloading mechanism to keep your state, actions and effects updated. You might not want to use this feature or Overmind does not correctly detect that hot reloading should be turned off. You can turn it off with an option.[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/api/app_options_hotreloading.ts)

```typescript
const overmind = createOvermind(config, {
  hotReloading: false
})
```

## options.delimiter

By default Overmind will create state paths using `.` as delimiter. This is used to give each state value an address and is used with the devtools. If any state keys uses `.` you will get weird behaviour in the devtools. You can now change this delimiter to a safe value, typically `' '` or `'|'` :

```typescript
const overmind = createOvermind(config, {
  delimiter: '.'
})
```


# createOvermindMock

The **createOvermindMock** factory creates an instance of Overmind which can be used to test actions. You can mock out effects and evaluate mutations performed during action execution.

{% tabs %}
{% tab title="overmind/actions.test.ts" %}

```typescript
import { createOvermindMock } from 'overmind'
import { config } from './'

describe('Actions', () => {
  describe('getPost', () => {
    test('should get post with passed id', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost(id) {
            return Promise.resolve({
              id
            })
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.mutations).toMatchSnapshot()
    })
    test('should handle errors', async () => {
      const overmind = createOvermindMock(config, {
        api: {
          getPost() {
            throw new Error('test')
          }
        }
      })

      await overmind.actions.getPost('1')

      expect(overmind.mutations).toMatchSnapshot()
    })
  })
})
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
It is important that you separate your **config** from the instantiation of Overmind, meaning that **createOvermind** should not be used in the same fail as the config you see imported here, it should rather be used where you render your application. This allows the config to be used for multiple purposes.
{% endhint %}


# createOvermindSSR

The **createOvermindSSR** factory creates an instance of Overmind which can be used on the server with server side rendering. It allows you to change state and extract the mutations performed, which can then be rehydrated on the client.

{% tabs %}
{% tab title="server/routePosts.ts" %}

```typescript
import { createOvermindSSR } from 'overmind'
import { config } from '../client/overmind'
import db from './db'

export default async (req, res) => {
  const overmind = createOvermindSSR(config)

  overmind.state.currentPage = 'posts'
  overmind.state.posts = await db.getPosts()

  const html = renderToString(
    // Whatever your view layer does to produce the HTML
  )

  res.send(`
<html>
  <body>
    <div id="app">${html}</div>
    <script>
      window.__OVERMIND_MUTATIONS = ${JSON.stringify(overmind.hydrate())}
    </script>
    <script src="/scripts/app.js"></script>
  </body>
</html>
`)
}
```

{% endtab %}
{% endtabs %}

## rehydrate

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize, rehydrate } from 'overmind'

export const onInitialize: OnInitialize = ({ state }) => {
  const mutations = window.__OVERMIND_MUTATIONS

  rehydrate(state, mutations)
}
```

{% endtab %}
{% endtabs %}


# derive

You can add derived state to your application. You access derived state like any other value, there is no need to call it as a function. The derived value is cached and will only update when any accessed state changes.

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { Derive } from 'overmind'

export type Item = {
  title: string
  completed: boolean
}

export type State = {
  items: Item[]
  completedItems: Derive<State, Item[]>
}

export const state: State = {
  items: [],
  completedItems: (state, rootState) =>
    state.items.filter(item => item.completed)
}
```

{% endtab %}
{% endtabs %}

The function defining your derived state receives two arguments. The first argument is the object the derived function is attached to. Ideally you use this argument to produce your derived state, though you can access the second argument which is the root state of the application. The root state allows you to access any state.

{% hint style="info" %}
Accessing **rootState** might cause unnecessary updates to the derived function as it will track more state, though typically not an issue
{% endhint %}

An other use case for derived is to return a function. This allows you to insert functions into your state tree which can execute logic, even based on existing state. Even the function itself might be changed out based on the state of the application.

{% tabs %}
{% tab title="overmind/state.ts" %}

```typescript
import { Derive } from 'overmind'

export type User = {
  name: string
}

export type State = {
  user: User
  tellUser: Derive<State, (message: string) => {}>
}

export const state: State = {
  user: {
    name: 'John'
  },
  tellUser: (state) =>
    (message) => console.log(message, ', ' + state.user.name)
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Using state inside the returned function will not be tracked. You have to access the state in the scope of the derived function
{% endhint %}


# effects

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import { User, Item } from './state'

export const api = {
  async getUser(): Promise<User> {
    const response = await fetch('/user')

    return response.json()
  },
  async getItem(id: number): Promise<Item> {
    const response = await fetch(`/items/${id}`)

    return response.json()
  }
}
```

{% endtab %}
{% endtabs %}

Effects is really just about exposing existing libraries or create your own APIs for doing side effects. When these effects are attached to the application they will be tracked by the devtools giving you additional debugging information. By “injecting” the effects this way also open up for better testability of your logic.


# events

Overmind emits events during execution of actions and similar. It can be beneficial to listen to these events for analytics or maybe you want to create a custom debugging experience. The following events can be listened to by adding a listener to the eventHub:

```typescript
overmind.eventHub.on('action:start', (execution) => {})
overmind.eventHub.on('action:end', (execution) => {})
overmind.eventHub.on('operator:start', (execution) => {})
overmind.eventHub.on('operator:end', (execution) => {})
overmind.eventHub.on('operator:async', (execution) => {})
overmind.eventHub.on('mutations', (executionAndMutations) => {})
overmind.eventHub.on('derived', (derived) => {})
overmind.eventHub.on('derived:dirty', (derivedPathAndFlush) => {})

// Only during development
overmind.eventHub.on('effect', (effectDetails) => {})
overmind.eventHub.on('getter', (getterDetails) => {})
overmind.eventHub.on('component:add', (componentDetails) => {})
overmind.eventHub.on('component:update', (componentDetails) => {})
overmind.eventHub.on('component:remove', (componentDetails) => {})
```


# json

Overmind wraps objects and arrays in your state structure with proxies. If you pass state to 3rd party libraries, to a service worker or similar, you should pass a long a copy of that state. This avoids the 3rd party tool from mutating your state when you do not want it to.

```typescript
import { json } from 'overmind'

const copy = json(someValue)
```

This function does a copy of any plain object or array, which are the only values that is wrapped with proxies. This ensures minimal work is done and keeps all other values alone.


# lazy

You can lazy load configurations. You do this by giving each configuration a key with a function that returns the config when called. To actually load the configurations you can either call an effect or an action with the key of the configuration to load.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { lazy } from 'overmind/config'

export const config = lazy({
  moduleA: async () => await import('./moduleA').config
})
```

{% endtab %}

{% tab title="overmind/moduleA/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
export const loadModule = async ({ actions }) => {
  await actions.lazy.loadConfig('moduleA')
}
```

{% endtab %}
{% endtabs %}


# merge

Allows you to merge configurations together.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import {IConfig } from 'overmind'
import { merge } from 'overmind/config'
import * as moduleA from './moduleA'
import * as moduleB from './moduleB'

export const config = merge(moduleA, moduleB)

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}

Note that merge can be useful to combine a root configuration with **namespaced** or **lazy** configuration.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import {IConfig } from 'overmind'
import { merge, namespaced, lazy } from 'overmind/config'
import { state } from './state'
import * as moduleA from './moduleA'
import { Config as ModuleB } from './moduleB'

export const config = merge(
  {
    state
  },
  namespaced({
    moduleA
  }),
  lazy({
    moduleB: async (): Promise<ModuleB> => await import('./moduleB').config
  })
)

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}


# namespaced

Allows you to namespace configurations by a key.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import {IConfig } from 'overmind'
import { namespaced } from 'overmind/config'
import * as moduleA from './moduleA'
import * as moduleB from './moduleB'

export const config = namespaced({
  moduleA,
  moduleB
})

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}


# onInitialize

If you need to run logic as the application initializes you can use the **onInitialize** hook. This is defined as an action and it receives the application instance as the input value. You can do whatever you want here. Set initial state, run an action, configure a router etc.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

export const onInitialize: OnInitialize = async ({
  state,
  actions,
  effects
}, overmind) => {
  const initialData = await effects.api.getInitialData()
  state.initialData = initialData
}
```

{% endtab %}

{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { onInitialize } from './onInitialize'
import { state } from './state'
import * as actions from './actions'

export const config = {
  onInitialize,
  state,
  actions
}

// For explicit typing check the Typescript guide
declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}
{% endtabs %}


# operators

Overmind also provides a functional API to help you manage complex logic. This API is inspired by asynchronous flow libraries like RxJS, though it is designed to manage application state and effects. If you want to create and use a traditional action “operator style” you define it like this:

```typescript
import { Operator, mutate } from 'overmind'

export const changeFoo: <T>() => Operator<T> = () =>
  mutate(({ state }) => {
    state.foo = 'bar'
  })
```

The **mutate** function is one of many operators. Operators are small composable pieces of logic that can be combined in many ways. This allows you to express complexity in a declarative way. You typically use the **pipe** operator in combination with the other operators to do this:

```typescript
import { Operator, pipe, debounce } from 'overmind'
import { QueryResult } from './state'
import * as o from './operators'

export const search: Operator<string> = pipe(
  o.setQuery(),
  o.filterValidQuery(),
  debounce(200),
  o.queryResult()
)
```

Any of these operators can be used with other operators. You can even insert a pipe inside an other pipe. This kind of composition is what makes functional programming so powerful.

## catchError

**async**

This operator runs if any of the previous operators throws an error. It allows you to manage that error by changing your state, run effects or even return a new value to the next operators.

```typescript
import { Operator, pipe, mutate, catchError } from 'overmind'

export const doSomething: Operator<string> = pipe(
  mutate(() => {
    throw new Error('foo')
  }),
  mutate(() => {
    // This one is skipped
  })
  catchError(({ state }, error) => {
    state.error = error.message

    return 'value_to_be_passed_on'
  }),
  mutate(() => {
    // This one continues executing with replaced value
  })
)
```

## debounce

When action is called multiple times within the set time limit, only the last action will move beyond the point of the debounce.

```typescript
import { Operator, pipe, debounce } from 'overmind'
import * as o from './operators'

export const search: Operator<string> = pipe(
  debounce(200),
  o.performSearch()
)
```

## filter

Stop execution if it returns false.

```typescript
import { Operator, filter } from 'overmind'

export const lengthGreaterThan: (length: number) => Operator<string> = (length) =>
  filter(function lengthGreaterThan(_, value) {
    return value.length > length
  })
```

## forEach

Allows you to pass each item of a value that is an array to the operator/pipe on the second argument.

```typescript
import { Operator, pipe, forEach } from 'overmind'
import { Post } from './state'
import * as o from './operators'

export const openPosts: Operator<string, Post[]> = pipe(
  o.getPosts(),
  forEach(o.getAuthor())
)
```

## fork

Allows you to execute an operator/pipe based on the matching key.

{% tabs %}
{% tab title="overmind/operators.ts" %}

```typescript
import { fork, Operator } from 'overmind'
import { User } from './state'

export const forkUserType: (paths: { [key: string]: Operator<User> }) => Operator<User> = (paths) =>
  fork(function forkUserType(_, user) {
    return user.type
  }, paths)
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Operator, pipe } from 'overmind'
import * as o from './operators'
import { UserType } from './state'

export const getUser: Operator<string, User> = pipe(
  o.getUser(),
  o.forkUserType({
    [UserType.ADMIN]: o.doThis(),
    [UserType.SUPERUSER]: o.doThat()
  })
)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
You have to use **ENUM** for these keys
{% endhint %}

## map

Returns a new value to the pipe. If the value is a promise it will wait until promise is resolved.

```typescript
import { Operator, map } from 'overmind'
import { User } from './state'

export const getEventTargetValue: () => Operator<Event, string> = () =>
  map(function getEventTargetValue(_, event) {
    return event.currentTarget.value
  })
```

## mutate

**async**

You use this operator whenever you want to change the state of the app. Any returned value is ignored.

```typescript
import { Operator, mutate } from 'overmind'

export const setUser: () => Operator<User> = () =>
  mutate(function setUser({ state }, user) {
    state.user = user
  })
```

## noop

This operator does absolutely nothing. Is useful when paths of execution is not supposed to do anything.

```typescript
import { Operator } from 'overmind'
import * as o from './operators'

export const doSomething: Operator = o.forkUserType({
  superuser: o.doThis(),
  admin: o.doThat(),
  other: o.noop()
})
```

## parallel

Will run every operator and wait for all of them to finish before moving on. Works like *Promise.all*.

```typescript
import { Operator, parallel } from 'overmind'
import * as o from './operators'

export const loadAllData: Operator = parallel(
  o.loadSomeData(),
  o.loadSomeMoreData()
)
```

## pipe

The pipe is an operator in itself. Use it to compose other operators and pipes.

```typescript
import { Operator, pipe } from 'overmind'
import { Item } from './state'
import * as o from './operators'

export const openItem: Operator<string, Item> = pipe(
  o.openItemsWhichIsAPipeOperator(),
  o.getItem()
)
```

## run

This operator allows you to run side effects. You can not change state and you can not return a value.

```typescript
import { Operator, run } from 'overmind'

export const doSomething: <T>() => Operator<T> = () =>
  run(function doSomething({ effects }) {
    effects.someApi.doSomething()
  })
```

## throttle

This operator allows you to ensure that if an action is called, the next action will only continue past this point if a certain duration has passed. Typically used when an action is called many times in a short amount of time.

```typescript
import { Operator, pipe, throttle } from 'overmind'
import * as o from './operators'

export const onMouseDrag: Operator<string> = pipe(
  throttle(200),
  o.handleMouseDrag()
)
```

## tryCatch

This operator allows you to scope execution and manage errors. This operator does not return a new value to the execution.

```typescript
import { Operator, pipe, tryCatch } from 'overmind'
import * as o from './operators'

export const doSomething: Operator<string> = tryCatch({
  try: o.somethingThatMightError(),
  catch: o.somethingToHandleTheError()
})
```

## wait

Hold execution for set time.

```typescript
import { Operator, pipe, wait } from 'overmind'
import * as o from './operators'

export const search: Operator<string> = pipe(
  wait(2000),
  o.executeSomething()
)
```

## waitUntil

Wait until a state condition is true.

```typescript
import { Operator, pipe, waitUntil } from 'overmind'
import * as o from './operators'

export const search: Operator<string> = pipe(
  waitUntil(state => state.count === 3),
  o.executeSomething()
)
```

## when

Go down the true or false path based on the returned value.

```typescript
import { Operator, when } from 'overmind'
import { User } from './state'

export const whenUserIsAwesome: (paths: { true: Operator<User>, false: Operator<User> }) => Operator<User> = (paths) => 
  when(function whenUserIsAwesome(_, user) {
    return user.isAwesome
  }, paths)
```


# reaction

Sometimes you need to react to changes to state. Typically you want to run some imperative logic related to something in the state changing.

```typescript
reaction(
  // Access and return some state to react to
  (state) => state.foo,

  // Do something with the returned value
  (foo) => {},

  {
    // If you return an object or array from the state you can set this to true.
    // The reaction will run when any nested changes occur as well
    nested: false,

    // Runs the reaction immediately
    immediate: false
  }
)
```

There are two points of setting up reactions in Overmind.

## onInitialize

The onInitialize hook is where you set up reactions that lives throughout your application lifetime. The reaction function returns a function to dispose it. That means you can give effects the possibility to create and dispose of reactions in any action.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize } from 'overmind'

export const onInitialize: OnInitialize = ({ effects }, instance) => {
  instance.reaction(
    ({ todos }) => todos,
    (todos) => effects.storage.saveTodos(todos),
    {
      nested: true
    }
  )
}
```

{% endtab %}
{% endtabs %}

## components

With components you typically use reactions to manipulate DOM elements or other UI related imperative libraries.

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

```typescript
import * as React from 'react'
import { useOvermind } from '../overmind'

const App: React.FC = () => {
  const { reaction } = useOvermind()

  React.useEffect(() => reaction(
    ({ currentPage }) => currentPage,
    () => {
      document.querySelector('#page').scrollTop = 0
    }
  ))

  return <div id="page"></div>
}

export default App
```

{% endtab %}

{% tab title="Angular" %}

```typescript
import { Component } from '@angular/core';
import { Store } from '../overmind'

@Component({
  selector: 'app-root',
  template: `
  <div id="page"></div>
  `
})
export class App {
  constructor(private store: Store) {}
  ngOnInit() {
    this.store.reaction(
      ({ currentPage }) => currentPage,
      () => {
        document.querySelector('#page').scrollTop = 0
      }    
    )
  }
}
```

{% endtab %}

{% tab title="Vue" %}

```typescript
<template>
  <div id="page"></div>
</template>
<script>
export default {
  mounted() {
    this.overmind.reaction(
      ({ currentPage }) => currentPage,
      () => {
        document.querySelector('#page').scrollTop = 0
      }     
    )
  }
}
</script>
```

{% endtab %}
{% endtabs %}


# rehydrate

It is possible to update the complete state of Overmind using the **rehydrate** tool. It allows you to update the state either with a state object or an array of mutations, typically collected from server side rendering.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { rehydrate } from 'overmind'

export const onInitialize = ({ state, effects }) => {
  // Grab mutations from a server rendered version
  const mutations = window.__OVERMIND_MUTATIONS

  rehydrate(state, mutations)

  // Grab a previous copy of the state, for example stored in
  // localstorage
  rehydrate(state, effects.storage.get('previousState') || {})
}
```

{% endtab %}
{% endtabs %}

The function takes into acount the state structure of Overmind which is based on objects where functions are derived state. That means it will leave derived state alone, resulting in them rather updating if any of their dependecies where updated by rehydration.


# statecharts

Statecharts is a configuration factory, just like **merge**, **namespaced** and **lazy**. It allows you to restrict what actions are to be run in certain states.

## statechart

The factory function you use to wrap an Overmind configuration. You add one or multiple charts to the configuration, where the key is the *id* of the chart.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {}> = {}

export default statechart(config, chart)
```

## initial

Define the initial state of the chart. When a parent chart enters a transition state, any nested chart will move to its initial transition state.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
}> = {
  initial: 'STATE_A'
}

export default statechart(config, chart)
```

## states

Defines the transition states of the chart. The chart can only be in one of these states at any point in time.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {},
    STATE_B: {}
  }
}

export default statechart(config, chart)
```

## entry

When a transition state is entered you can optionally run an action. It also runs if it is the initial state.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      entry: 'someActionName'
    },
    STATE_B: {}
  }
}

export default statechart(config, chart)
```

## exit

When a transition state is changed, any exit defined in current transition state will be run first. Nested charts in a transition state with an exit defined will run before parents.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      entry: 'someActionName',
      exit: 'someOtherActionName'
    },
    STATE_B: {}
  }
}

export default statechart(config, chart)
```

## on

Unlike traditional statecharts Overmind uses its actions as transition types. This keeps a cleaner chart definition and when using Typescript the actions will have correct typing related to their payload. The actions defined are the only actions allowed to run. They can optionally lead to a new transition state, even conditionally lead to a new transition state.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      on: {
        // Allow execution, but stay on this transition state
        someAction: null,

        // Move to new transition state when executed
        someOtherAction: 'STATE_B',

        // Conditionally move to a new transition state
        someConditionalAction: {
          target: 'STATE_B',
          condition: state => state.isTrue
        }
      }
    },
    STATE_B: {}
  }
}

export default statechart(config, chart)
```

## nested

A nested statechart will operate within its parent transition state. The means when the parent transition state is entered or exited any defined **entry** and **exit** actions will be run. When the parent enters its transition state the **initial** state of the child statechart(s) will be activated.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const nestedChart: Statechart<typeof config, {
  FOO: void
  BAR: void
}> = {
  initial: 'FOO',
  states: {
    FOO: {
      on: {
        transitionToBar: 'BAR'
      }
    },
    BAR: {
      on: {
        transitionToFoo: 'FOO'
      }
    }
  }
}

const chart: Statechart<typeof config, {
  STATE_A: typeof nestedChart
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      on: {
        transitionToStateB: 'STATE_B'
      },
      chart: nestedChart
    },
    STATE_B: {
      on: {
        transitionToStateA: 'STATE_A'
      }
    }
  }
}

export default statechart(config, chart)
```

## parallel

Multiple statecharts will run in parallel. Either for the factory configuration or nested charts. You can add the same chart multiple times behind different ids.

```typescript
import { Statechart, statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  actions,
  state
}

const chart: Statechart<typeof config, {
  STATE_A: void
  STATE_B: void
}> = {
  initial: 'STATE_A',
  states: {
    STATE_A: {
      on: {
        transitionToStateB: 'STATE_B'
      }
    },
    STATE_B: {
      on: {
        transitionToStateA: 'STATE_A'
      }
    }
  }
}

export default statechart(config, {
  chartA: chart,
  chartB: chart
})
```

{% hint style="info" %}
Also the nested **chart** property of charts can contain parallel charts
{% endhint %}

## matches

The matches API is used in your components to identify what state your charts are in. It is accessed on the **state**.

```typescript
// Given that you have added statecharts to the root configuration
state.matches({
  STATE_A: true
})

// Nested chart
state.matches({
  STATE_A: {
    FOO: true
  }
})

// Parallel
state.matches({
  chartA: {
    STATE_A: true
  },
  chartB: {
    STATE_B: true
  }
})

// Negative check
state.matches({
  chartA: {
    STATE_A: true
  },
  chartB: {
    STATE_B: false
  }
})
```


# Overmind

frictionless state management

> Web application development is about **defining**, **changing** and **consuming state** to produce a user experience. Overmind aims for a developer experience where that is all you focus on, reducing the orchestration of state management to a minimum. Making you a **happier** and more **productive** developer!

{% embed url="<https://overmindjs.changefeed.app/general/v23.1>" %}

## APPLICATION INSIGHT

Develop the application state, effects and actions without leaving [VS Code](https://code.visualstudio.com/), or use the standalone development tool. Everything that happens in your app is tracked and you can seamlessly code and run logic to verify that everything works as expected without necessarily having to implement UI.

![](/files/-Ly_HBec6C-YihjahYdA)

## A SINGLE STATE TREE

Building your application with a single state tree is the most straight forward mental model. You get a complete overview, but can still organize the state by namespacing it into domains. The devtools allows you to edit and mock out state.

```typescript
{
  isAuthenticating: false,
  dashboard: {
    issues: [],
    selectedIssueId: null,
  },
  user: null,
  form: new Form()
}
```

## SEPARATION OF LOGIC

Separate 3rd party APIs and logic not specific to your application by using **effects**. This will keep your application logic pure and without low level APIs cluttering your code.

{% tabs %}
{% tab title="api.js" %}

```javascript
export const fetchItems = async () {
    const response = await fetch('/api/items')

    return response.json()
  }
}
```

{% endtab %}

{% tab title="actions.js" %}

```typescript
export const loadApp = ({ state, effects }) => {
  state.items = await effects.api.fetchItems()
}
```

{% endtab %}
{% endtabs %}

## SAFE AND PREDICTABLE CHANGES

When you build applications that perform many state changes things can get out of hand. In Overmind you can only perform state changes from **actions** and all changes are tracked by the development tool.

```javascript
export const getItems = async ({ state, effects }) => {
  state.isLoadingItems = true
  state.items = await effects.api.fetchItems()
  state.isLoadingItems = false
}
```

## COMPLEXITY TOOLS

Even though Overmind can create applications with only plain **state** and **actions**, you can use **opt-in** tools like **functional operators**, **statecharts, statemachines** and state values defined as a **class,** to manage complexities of your application.

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

```javascript
export const search = pipe(
  mutate(({ state }, query) => {
    state.query = query
  }),
  filter((_, query) => query.length > 2),
  debounce(200),
  mutate(async ({ state, effects }, query) => {
    state.isSearching = true
    state.searchResult = await effects.getSearchResult(query)
    state.isSearching = false
  })
)
```

{% endtab %}

{% tab title="Statechart" %}

```javascript
const loginChart = {
  initial: 'LOGIN',
  states: {
    LOGIN: {
      on: {
        changeUsername: null,
        changePassword: null,
        login: 'AUTHENTICATING'
      }
    },
    AUTHENTICATING: {
      on: {
        resolveUser: 'AUTHENTICATED',
        rejectUser: 'ERROR'
      }
    },
    AUTHENTICATED: {
      on: {
        logout: 'LOGIN'
      }
    },
    ERROR: {
      on: {
        tryAgain: 'LOGIN'
      }
    }
  }
}
```

{% endtab %}

{% tab title="Statemachines" %}

```typescript
export const state = {
  mode: statemachine({
    initial: 'unauthenticated',
    states: {
      unauthenticated: ['authenticating'],
      authenticating: ['unauthenticated', 'authenticated'],
      authenticated: ['unauthenticating'],
      unauthenticating: ['unauthenticated', 'authenticated']
    }
  }),
  user: null,
  error: null
}
```

{% endtab %}

{% tab title="Class state" %}

```javascript
class LoginForm() {
  private username = ''
  private password = ''
  private validationError = ''
  changeUsername(username) {
    this.username = username
  }
  changePassword(password) {
    if (!password.match([0-9]) {
      this.validationError = 'You need some numbers in your password'
    }
    this.password = password
  }
  isValid() {
    return Boolean(this.username && this.password) 
  }
}

export const state = {
  loginForm: new LoginForm()
}
```

{% endtab %}
{% endtabs %}

## SNAPSHOT TESTING OF LOGIC

Bring in your application configuration of state, effects and actions. Create mocks for any effects. Take a snapshot of mutations performed in an action to ensure all intermediate states are met.

```javascript
import { createOvermindMock } from 'overmind'
import { config } from './'

test('should get items', async () => {
  const overmind = createOvermindMock(config, {
    api: {
      fetchItems: () => Promise.resolve([{ id: 0, title: "foo" }])
    }
  })

  await overmind.actions.getItems()

  expect(overmind.mutations).toMatchSnapshot()
})
```

## WE WROTE THE TYPING

Overmind has you covered on typing. If you choose to use Typescript the whole API is built for excellent typing support. You will not spend time telling Typescript how your app works, Typescript will tell you!

## RUNNING CODESANDBOX

![](/files/-LyeprUbhOErEqwCnRkJ)

Overmind is running the main application of [codesandbox.io](https://codesandbox.io). Codesandbox, with its state and effects complexity, benefits greatly combining Overmind and Typescript.


# Introduction

In this introduction you will get an overview of Overmind and how you can think about application development. We will be using [REACT](https://reactjs.org/) to write the UI, but you can use Overmind with [VUE](https://vuejs.org/) and [ANGULAR](https://angular.io/) if either of those is your preference.

{% hint style="info" %}
If you rather want to go right ahead and set up a local project, please have a look at the [QUICKSTART](/v23.1/quickstart) guide.
{% endhint %}

Before we move on, have a quick look at this sandbox. It is a simple counter application and it gives you some foundation before talking more about Overmind and building applications.

{% embed url="<https://codesandbox.io/s/overmind-counter-c4tuh?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

## Application state VS Component state

First of all we have to talk about **application** and **component** state. In the counter example above we chose to define our **count** state as application state, outside of the component. We could have defined the count inside the component instead and the application would work exactly the same. So why did we choose application state?

If the count example above was the entire application it would not make any sense to introduce application state and Overmind. But if you were to increase the scope of this simple application you would be surprised how quickly you get into the following scenarios:

1. **You want to introduce an other component that needs to know about the current state of the count.** This new component can not be a parent of the component owning the count state. It can not be a sibling either. It has to be a child. If it is not an immediate child the count state has to be passed down the component tree until it reaches your new component.
2. **You want to remember the count, even though it is not shown in the UI**. Your count is behind one of multiple tabs in the UI. When the user changes the tabs you do not want the count to reset. The only way to ensure this is to move the count state up to a parent component that is no longer a child of the tab and then pass the count state back down again.
3. **You want to change the count from a side effect**. You have a websocket connection which changes the count when a message is received. If you want to avoid this websocket connection to open and close as the component mounts and unmounts you will have to move the websocket connection up the component tree.
4. **You want to change the count as part of multiple changes**. When you click the increase count button you need to change both the count state and an other state related to a different part of the UI. To be able to change both states at the same time, they have to live inside the same component, which has to be a parent of both components using the state.

Introducing these scenarios we said: **You want**. In reality we rarely know exactly what we want. We do not know how our state and components will evolve. And this is the most important point. By using application state instead of component state you get flexibility to manage whatever comes down the road without having to refactor wrong assumptions.

**So is component state bad?** No, certainly not. You do not want to overload your application state with state that could just as well have been inside a component. The tricky thing is to figure out when that is absolutely the case. For example:

1. **Modals should certainly be component state?** Not all modals are triggered by a user interaction. A profile modal might be triggered by clicking a profile picture, but also open up when a user opens the application and is missing information.
2. **The active tab should certainly be component state?** The active tab might be part of the url query, `/user?tab=count`. That means it should rather be a hyperlink where your application handles the routing and provides state to identify the active tab.
3. **Inputs should certainly be component state?** If the input is part of an application flow, you might want to empty out the content of that input related to other changes, or even change it to something else.

How you want to go about this is totally up to you. We are not telling you exactly how to separate application and component state. What we can tell you though; **“If you lean towards application state your are more flexible to future changes”**.

## Defining state

As you can see in the count example we added a state object when we created the instance.

```javascript
createOvermind({
  state: {
    count: 0
  },
  ...
})
```

This state object will hold all the application state, we call it a *single state tree*. That does not mean you define all the state in one file and we will talk more about that later. For now let us talk about what you put into this state tree.

A single state tree typically favours serializable state. That means state that can be `JSON.parse` and `JSON.stringify` back and forth. It can be safely passed between the client and the server, localStorage or to web workers. You will use **strings**, **numbers**, **booleans**, **arrays**, **objects** and **null**. Overmind also has the ability to allow you define state values as class instances, even serializing back and forth. You can read more about that in [State](/v23.1/core/defining-state).

## Defining actions

When you need to change your state you define actions. Overmind only allows changing the state of the application inside the actions. An error will be thrown if you try to change the state inside a component. The actions are plain functions/methods. The only thing that makes them special is that they all receive a preset first argument, called **the context**:

```javascript
createOvermind({
  state: {
    count: 0
  },
  actions: {
    increaseCount({ state }) {
      state.count++;
    },
    decreaseCount({ state }) {
      state.count--;
    }
  }
})
```

Here we can see that we [DESTRUCTURE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) the context to grab the **state**. You can also access other actions on the context:

```javascript
createOvermind({
  state: {
    count: 0
  },
  actions: {
    increaseCount({ state, actions }) {
      state.count++;
      actions.decreaseCount()
    },
    decreaseCount({ state }) {
      state.count--;
    }
  }
})
```

And as we will see later you will also be using **effects** from the context.

## Increasing complexity

Now we will move to a more complex example. Please have a look:

{% embed url="<https://codesandbox.io/s/overmind-todomvc-simple-097zs?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

We have now separated out the Overmind related logic into its own file, **app.js**. This file creates the Overmind instance and also exports how the components will interact with the state and the actions, the hook called **useApp**. Vue and Angular has other mechanisms conventional to those frameworks where application state and actions can be accessed.

## References

What to take notice of is how we store the **todos** of this application.

```javascript
createOvermind({
  state: {
    ...
    todos: {},
    ...
  },
  ...
})
```

It is just an empty object. You might intuitively think of a list of todos as an array. Not blaming you, it makes total sense. That said, when you work with entities that has a unique identifier, typically an *id* property, you are better off storing them in an object. Each key in this object will be the unique identifier of a todo. For example:

```javascript
{
  'todo-1': {
    id: 'todo-1',
    title: 'My Todo',
    completed: false
  },
  'todo-2': {
    id: 'todo-2',
    title: 'My Other Todo',
    completed: true
  },
}
```

When you need to reference a todo, for example a component wants to reference a todo to toggle its completed state or maybe delete one, you will pass “todo-1” or “todo-2” as a reference instead of the todo itself.

Working with references this way avoids logic where you need to **find** a todo in an array or **filter**/**splice** out a todo to delete it from an array. You simply just point to the todos state to grab or delete it:

```javascript
state.todos[myReference]

delete state.todos[myReference]
```

Using references also ensures that only one instance of any todo will live in your state tree. The todo itself lives on the **todos** state, while everything else in the state tree references a todo by using its id. For example our **editingTodoId** state uses the id of a todo to reference which todo is currently being edited.&#x20;

## Deriving state

Looking through the example you have probably noticed these:

```javascript
createOvermind({
  state: {
    ...,
    currentTodos: ({ todos, filter }) => {
      return Object.values(todos).filter(todo => {
        switch (filter) {
          case 'active':
            return !todo.completed;
          case 'completed':
            return todo.completed;
          default:
            return true;
        }
      });
    },
    activeTodoCount: ({ todos }) => {
      return Object.values(todos).filter(todo => !todo.completed).length;
    },
    hasCompletedTodos: ({ todos }) => {
      return Object.values(todos).some(todo => todo.completed);
    },
    isAllTodosChecked: ({ currentTodos }) => {
      return currentTodos.every(todo => todo.completed);
    },
  },
  ...
})
```

Our state tree is concerned with state values that you will change using actions. But you can also automatically produce state values based on existing state. An example of this would be to list the **currentTodos**. It uses the todos and filter state to figure out what todos to actually display. Sometimes this is called computed state. We call it **derived** state.

Any function you insert into the state tree is treated as derived state. That means these functions receives a preset first argument which is the immediate state, the state object the derived is attached to. In bigger applications you might also need to use the second argument, which is the root state of the application. The derived will automatically track whatever state you use and then flag itself as dirty whenever it changes. If derived state is used while being dirty, the function will run again. If it is not dirty a cached value is returned.

## Effects

Now let us move into an even more complex application. Here we have added **effects**. Specifically effects to handle routing, storing todos to local storage and producing unique ids for the todos. We have added an **onInitialize** hook which is a special function Overmind runs when the application starts.

{% embed url="<https://codesandbox.io/s/overmind-todomvc-2im6p?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

You can think of effects as a contract between your application and the outside world. You write an effect API of **what** your application needs and some 3rd party tool or native JavaScript API will implement **how** to provide it. Let us look at the router:

```javascript
createOvermind({
  ...,
  effects: {
    ...,
    router: {
      initialize(routes) {
        Object.keys(routes).forEach(url => {
          page(url, ({ params }) => routes[url](params));
        });
        page.start();
      },
      goTo(url) {
        page.show(url);
      },
    },
  }
})
```

The router uses the [PAGE](https://www.npmjs.com/package/page) tool to manage routing. It takes a “url to action” option that makes sense for this application, but you could define this however you wanted.

```javascript
effects.router.initialize({
  '/': () => actions.changeFilter('all'),
  '/active': () => actions.changeFilter('active'),
  '/completed': () => actions.changeFilter('completed'),
});
```

This argument passed is transformed into something Page can understand. What this means is that we can easily switch out Page with some other tool later if we wanted to, or maybe if the app ran in different environments you could change out the implementation of the router dynamically. We were also able to combine **page** and **page.start** behind one method, which cleans up our application code. We did the same for the **storage** effect. We use localStorage and JSON.parse/JSON.stringify behind a single method.

## Scaling up the application

Defining all the state, actions and effects on one object would not work very well for a large application. A convention in Overmind is to split these concepts into different files behind folders representing a domain of the application. In this next sandbox you can see how we split up state, actions and effects into different files. They are all exposed through a main file representing that domain, in this case “the root domain”:

{% embed url="<https://codesandbox.io/s/overmind-todomvc-split-xdh41?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

Also notice that we have split up the instantiation of Overmind from the definition of the application. What this allows us to do is reuse the same application configuration for testing purposes and/or server side rendering. We separate the definition from the instantiation.

To scale up your code even more you can split it into **namespaces**. You can read more about that in the [STRUCTURING THE APP](/v23.1/core/structuring-the-app) guide.

## Get to know Typescript

Now that we have insight into the building blocks of Overmind it is time to introduce typing. If you are already familiar with [TYPESCRIPT](https://www.typescriptlang.org/) you will certainly enjoy the minimal typing required to get full type safety across your application. If you are unfamiliar with Typescript Overmind is a great project to start using it, for the very same reason.

Have a look at this new project where we have typed the application:

{% hint style="info" %}
You have to **OPEN IN EDITOR** to get the full Typescript experience.
{% endhint %}

{% embed url="<https://codesandbox.io/s/overmind-todomvc-typescript-39h7y?fontsize=14&hidenavigation=1&theme=dark&view=editor&runonclick=1>" %}

As you can see we only have to add an **Action** type to our functions and optionally give it an input type. This is enough for the action to give you all information about the application. Try changing some code and even add some code to see how Typescript helps you to explore the application and ensure that you implement new functionality correctly.

If you go to the **state.ts** file and change the type:

```typescript
export type State = {
  ...,
  newTodoTitle: string
  ...
}
```

to:

```typescript
export type State = {
  ...,
  todoTitle: string
  ...
}
```

You can now visit the **actions.ts** file and the **AddTodo.tsx** component. As you can see Typescript yells because the typing is now wrong. This is very powerful in complex projects which moves fast. The reason being that you can safely rename and refactor without worrying about breaking the code.

To learn more about Overmind and Typescript read the [TYPESCRIPT](https://www.overmindjs.org/guides/beginner/05_typescript) documentation.

## Development tool

Overmind also ships with its own development tool. It can be installed as a [VSCODE PLUGIN](https://marketplace.visualstudio.com/items?itemName=christianalfoni.overmind-devtools-vscode) or installed as an NPM package. The development tool knows everything about what is happening inside the application. It shows you all the state, running actions and connected components. By default Overmind connects automatically to the devtool if it is running. Try now by going to the **index.tsx** file and change:

```typescript
export const overmind = createOvermind(config, {
  devtools: false,
});
```

to:

```typescript
export const overmind = createOvermind(config, {
  devtools: true,
});
```

Go to your terminal and use the NPM executor to instantly fire up the development tool.

```
npx overmind-devtools@latest
```

Refresh the sandbox preview and you should see the devtools populated with information from the application.

{% hint style="info" %}
This only works in **CHROME** when running on codesandbox.io, due to domain security restrictions. It works on all browsers when running your project locally.
{% endhint %}

![](/files/-Ly_Ye8-PCJwaz9lUhuJ)

Here we get an overview of the current state of the application, including our derived state. If we move to the next tab we get an overview of the execution. We have not triggered any actions yet, but our **onInitialized** hook has run and triggered some logic.

![](/files/-Ly_YjTVWjycuO_dIxXo)

Here we can see that we grabbing todos from local storage and initializing our router. We can also see that the router instantly fires off our **changeFilter** action causing a state change on the filter. At the end we can see that our reaction triggered, saving the todos.

{% hint style="info" %}
You might wonder why the reaction triggered when it was defined after we changed the **todos** state. Overmind batches up changes to state and *flushes* at optimal points in the execution. For example when an action ends or some asynchronous code starts running. The reaction reacts to these flushes, just like components do.
{% endhint %}

Moving on we also get insight into components looking at our application state:

![](/files/-Ly_Yxpz7Z9HxOvpv-nB)

Currently two components are active in the application and we can also see what state they are looking at.

A chronological list of all state changes and effects run is available on the next tab. This can be useful with asynchronous code where actions changes state “in between” each other.

![](/files/-Ly_Z1fI66LDL5MCNQkc)

Now, let us try to add a new todo and see what happens.

![](/files/-Ly_Z7j6WSVu9swkIksn)

Our todo has been added and we can even see how the derived state was affected by this change. Looking at our actions tab we can see what state changes were performed and by hovering the mouse on the yellow label up right you get information about what components and derived were affected by state changes in this action.

![](/files/-Ly_ZE0yRYU9_L71s3WK)

## Managing complexity

Overmind gives you a basic foundation with its **state**, **actions** and **effects**. As mentioned previously you can split these up into multiple namespaces to organize your code. This manages the complexity of scaling. There is also a complexity of reusability and managing execution over time. The **operators** API allows you to split your logic into many different composable parts. With operators like **debounce**, **waitUntil** etc. you are able to manage execution over time. With the latest addition of **statecharts** you have the possiblity to manage the complexity of state and interaction. What interactions should be allowed in what states. And with state values as **class instances** you are able to co-locate state with logic.

The great thing about Overmind is that none of these concepts are forced upon you. If you want to build your entire app in the root namespace, only using actions, that is perfectly fine. You want to bring in operators for a single action to manage time complexity, do that. Or do you have a concept where you want to safely control what actions can run in certain states, use a statechart. Overmind just gives you tools, it is up to you to determine if they are needed or not.

## Moving from here

We hope this introduction got you excited about developing applications and working with Overmind. From this point you can continue working with [CODESANDBOX.IO](https://codesandbox.io/) or set up a local development flow. It is highly encouraged to use Overmind with Typescript, it does not get any more complex than what you see in this simple TodoMvc application.

Move over to the [QUICKSTART](/v23.1/quickstart) to get help setting up your project. The other guides will give you a deeper understanding of how Overmind works. If you are lost please talk to us on [DISCORD](https://discord.gg/YKw9Kd) and we are happy to help. And yeah… have fun! :-)


# Quickstart

From the command line install the Overmind package:

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

```
npm install overmind overmind-react
```

{% endtab %}

{% tab title="Vue" %}

```
npm install overmind overmind-vue
```

{% endtab %}

{% tab title="Angular" %}

```
npm install overmind overmind-angular
```

{% endtab %}
{% endtabs %}

### Setup

Now set up a simple application like this:

{% tabs %}
{% tab title="overmind/state.js" %}

```javascript
export const state = {
  title: 'My App'
}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

And fire up your application in the browser or whatever environment your user interface is to be consumed in by the users.

Move on with the specific view layer of choice to connect your app:

[**REACT** ](/v23.1/views/react)**-** [**ANGULAR**](/v23.1/views/angular) **-** [**VUE**](/v23.1/views/vue)


# How to learn

To learn any new tool it is important to have some goal unrelated to the tool itself. Maybe you have a pet project or a project at work you want to try it on. There is a lot on the menu on the left here, so let us give you some pointers to the most important docs to understand Overmind.

* [**The introduction video**](https://youtu.be/82Aq_ujnBQw) gives you a quick overview of what Overmind is
* You will benefit from getting into the overall structure with [**Configuration**](/v23.1/core/structuring-the-app)**,** then moving on to the specific concepts of [**State**](/v23.1/core/defining-state)**,** [**Actions**](/v23.1/core/writing-application-logic) and [**Effects**](/v23.1/core/running-side-effects)
* If you use Typescript it can be a good idea to already now explore how you use Overmind with [**Typescript**](/v23.1/core/typescript)
* Ready to start building something? Check of the view packages for [**React**](/v23.1/views/react), [**Angular**](/v23.1/views/angular) or [**Vue**](/v23.1/views/vue), to get you started
* Once you got a feel for it, the **Connecting components** guide will give you some more insight into how you use your state in the components
* From here it is totally up to you! Good luck and please visit our Discord channel for support


# Videos

## Overmind introduction

{% embed url="<https://youtu.be/82Aq_ujnBQw>" %}

## Devtools introduction

{% embed url="<https://youtu.be/j_dzXucq3E4>" %}

## Replacing Vuex with Overmind

{% embed url="<https://youtu.be/O5FMIXwYLAA>" %}

## VSCode extension

{% embed url="<https://youtu.be/P4CwiC0f56Y>" %}


# FAQ

## The devtool is not responding?

First… try to refresh your app to reconnect. If this does not work make sure that the entry point in your application is actually creating an instance of Overmind. The code **createOvermind(config)** has to run to instantiate the devtools.

## The devtools does not open in VS Code?

Restart VS Code

## My operator actions are not running?

Operators are identified with a Symbol. If you happen to use Overmind across packages you might be running two versions of Overmind. The same goes for core package and view package installed out of version sync. Make sure you are only running on package of Overmind by looking into your **node\_modules** folder.


# Devtools

## VS Code

For the best experience you should install the [OVERMIND DEVTOOLS](https://marketplace.visualstudio.com/items?itemName=christianalfoni.overmind-devtools-vscode) extension. This will allow you to work on your application without leaving the IDE at all.

![](/files/-Ly_HBec6C-YihjahYdA)

{% hint style="info" %}
If you are using the **Insiders** version of VSCode the extension will not work. It seems to be some extra security setting.
{% endhint %}

## Standalone app

Alternatively you can install the standalone application of the devtools. You can start it with the NPM executor as:

```javascript
npx overmind-devtools@latest
```

{% hint style="info" %}
Adding **@latest** just ensures that you break any caching, meaning you will always run the latest version
{% endhint %}

You can also install the devtools with your project, allowing you to lock a specific version of the devtools to your project:

```javascript
npm install overmind-devtools
```

With the package [CONCURRENTLY](https://www.npmjs.com/package/concurrently) you can start the devtools as you start your build process:

```
npm install overmind-devtools concurrently
```

{% code title="package.json" %}

```javascript
{
  ...
  "scripts": {
    "start": "concurrently \"overmind-devtools\" \"someBuildTool\""
  },
  ...
}
```

{% endcode %}

## Connecting from the application

When you create your application it will automatically connect through **localhost:3031**, meaning that everything should just work out of the box. If you need to change the port, connect the application over a network (mobile development) or similar, you can configure how the application connects:

```javascript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config, {
  devtools: '10.0.0.1:3031'
})
```

### Connecting on Chromebook

ChromeOS does not expose localhost as normal. That means you need to connect with **penguin.termina.linux.test:3031**, or you can use the following plugin to forward **localhost:**

{% embed url="<https://chrome.google.com/webstore/detail/connection-forwarder/ahaijnonphgkgnkbklchdhclailflinn/related?hl=en-US>" %}

## Hot Module Replacement

A popular concept introduced by Webpack is [HMR](https://webpack.js.org/concepts/hot-module-replacement/). It allows you to make changes to your code without having to refresh. Overmind automatically supports HMR. That means when **HMR** is activated Overmind will make sure it updates and manages its state, actions and effects. Even the devtools will be updated as you make changes.

Typically you add this, here showing with React:

```typescript
import React from 'react'
import { render } from 'react-dom'
import { createOvermind } from 'overmind'
import { Provider } from 'overmind-react'
import { config } from './overmind'
import { App } from './components/App'


const overmind = createOvermind(config)

render(<Provider value={overmind}><App /></Provider>, document.querySelector('#app'))

// Allows this module to run again without refresh,
// meaning "createOvermind" runs again and automatically
// reconfigures
if (module.hot) {
  module.hot.accept()
}
```

Though you can also manually only update Overmind by:

{% tabs %}
{% tab title="index.js" %}

```typescript
import React from 'react'
import { render } from 'react-dom'
import { overmind } from './overmindInstance'
import { Provider } from 'overmind-react'
import { App } from './components/App'

render(<Provider value={overmind}><App /></Provider>, document.querySelector('#app'))


```

{% endtab %}

{% tab title="overmindInstance.js" %}

```javascript
import { createOvermind } from 'overmind'
import { config } from './overmind'

export const overmind = createOvermind(config)

// When this module runs again "createOvermind" is run
// and it automatically reconfigures
if (module.hot) {
  module.hot.accept()
}
```

{% endtab %}
{% endtabs %}


# Configuration

Overmind is based on a core concept of:

`{ state, actions, effects }`

This data structure is called **the configuration** of your application. If it is a simple application you might have a single configuration, but typically you will create multiple of them and use tools to merge them together into one big configuration. But before we look at the scalability of Overmind, let’s talk about file structure.

## Domains

As your application grows you start to separate it into different domains. A domain might be closely related to a page in your application, or maybe it is strictly related to managing some piece of data. It does not matter. You define the domains of your application and they probably change over time as well. What matters in the context of Overmind though is that each of these domains will contain their own state, actions and effects. So imagine a file structure of:

```
overmind/
  state.ts
  actions.ts
  effects.ts
  index.ts
```

In this structure we are splitting up the different components of the configuration. This is a good first step. The **index** file acts as the file that brings the **state**, **actions** and **effects** together.

But if we want to split up into actual domains it would look more like this:

```
overmind/
  posts/
    state.ts
    actions.ts
    effects.ts
    index.ts
  admin/
    state.ts
    actions.ts
    effects.ts
    index.ts
  index.ts
```

In this case each domain **index** file bring its own state, actions and effects together and the **overmind/index** file is responsible for bringing the whole configuration together.

## The state file

You will typically define your **state** file by exporting a single constant named *state*.

{% tabs %}
{% tab title="overmind/posts/state.js" %}

```typescript
export const state = {
  posts: []
}
```

{% endtab %}

{% tab title="overmind/admin/state.js" %}

```typescript
export const state: State = {
  users: []
}
```

{% endtab %}
{% endtabs %}

## The actions file

The actions are exported individually by giving them a name and a definition.

{% tabs %}
{% tab title="overmind/posts/actions.js" %}

```typescript
export const getPosts = async () => {}

export const addNewPost = async () => {}
```

{% endtab %}

{% tab title="overmind/admin/actions.js" %}

```typescript
export const getUsers = async () => {}

export const changeUserAccess = async () => {}
```

{% endtab %}
{% endtabs %}

## The effects file

The effects are also exported individually where you would typically organize the methods in an object, but this could have been a class instance or just a plain function as well.

{% tabs %}
{% tab title="overmind/posts/effects.js" %}

```typescript
export const postsApi = {
  getPostsFromServer() {}
}
```

{% endtab %}

{% tab title="overmind/admin/effects.js" %}

```typescript
export const adminApi = {
  getUsersFromServer() {}
}
```

{% endtab %}
{% endtabs %}

You might find it more useful to define a single effects file at the root of your application and rather create a file for each effect.

{% tabs %}
{% tab title="overmind/effects/index.js" %}

```typescript
import * as api from './api'

export {
  api
}
```

{% endtab %}

{% tab title="overmind/effects/api.js" %}

```typescript
export const getUser = async () => {}

export const getPosts = async () => {}
```

{% endtab %}
{% endtabs %}

## Bring it together

Now let us export the state, actions and effects for each module and bring it all together into a **namespaced** configuration.

{% tabs %}
{% tab title="overmind/posts/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export {
  state,
  actions,
  effects
}
```

{% endtab %}

{% tab title="overmind/admin/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export {
  state,
  actions,
  effects
}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { namespaced } from 'overmind/config'
import * as posts from './posts'
import * as admin from './admin'

export const config = namespaced({
  posts,
  admin
})
```

{% endtab %}
{% endtabs %}

We used the **namespaced** function to put the state, actions and effects from each domain behind a key. In this case the key is the same as the name of the domain itself. This is an effective way to split up your app.

You can also combine this with the **merge** tool to have a top level domain.

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { merge, namespaced } from 'overmind/config'
import { state } from './state'
import * as posts from './posts'
import * as admin from './admin'

export const config = merge(
  {
    state
  },
  namespaced({
    posts,
    admin
  })
)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Even though you split up into different domains each domain has access to the state of the whole application. This is an important feature of Overmind which allows you to scale up and explore the domains of the application without having to worry about isolation.
{% endhint %}


# State

Typically we think of the user interface as the application itself. But the user interface is really just there to allow a user to interact with the application. This interface can be anything. A browser window, native, sensors etc. It does not matter what the interface is, the application is still the same.

The mechanism of communicating from the application to the user interface is called **state**. A user interface is created by **transforming** the current state. To communicate from the user interface to the application an API is exposed, called **actions** in Overmind. Any interaction can trigger an action which changes the state, causing the application to notify the user interface about any updated state.

![](/files/-Ly__8wUlT2Mz5acMDgQ)

## State tree

Overmind is structured as a single state tree. That means all of your state can be accessed through a single object, called the **state**. This state tree will hold values which describes different states of your application. The tree branches out using plain objects, which can be considered **branches** of your state tree.

```javascript
{ // branch
  modes: ['issues', 'admin'],
  currentModeIndex: 0,
  admin: { // branch
    currentUserId: null,
    users: { // branch
      isLoading: false,
      data: {},
      error: null
    },
  },
  issues: { // branch
    sortBy: 'name',
    isLoading: false,
    data: {},
    error: null
  }
}
```

## State tree values

The following are values to be used with the state tree.

### Objects

The plain objects are what **branches** out the tree. It is not really considered a value in itself, it is a state branch holding values.

### Arrays

Arrays are similar to objects in the sense that they hold other values, but instead of keys pointing to values you have indexes. That means it is ideal for iteration. But more often than not objects are actually better at managing lists of values. We can actually do fine without arrays in our state. It is when we produce the actual user interface that we usually want arrays. You can learn more about this in the [MANAGING LISTS](/v23.1/guides-1/managing-lists) guide.

### Strings

Strings are of course used to represent text values. Names, descriptions and whatnot. But strings are also used for ids, types, etc. Strings can be used as values to reference other values. This is an important part in structuring state. For example in our **objects** example above we chose to use an array to represent the modes, using an index to point to the current mode, but we could also do:

```javascript
{
  modes: {
    issues: 0,
    admin: 1 
  },
  currentMode: 'issues'
  ...
}
```

Now we are referencing the current mode with a string. In this scenario you would probably stick with the array, but it is important to highlight that objects allow you to reference things by string, while arrays reference by number.

### Numbers

Numbers of course represent things like counts, age, etc. But just like strings, they can also represent a reference to something in a list. Like we saw in our **objects** example, to define what the current mode of our application is, we can use a number. You could say that referencing things by number works very well when the value behind the number does not change. Our modes will most likely not change and that is why an array and referencing the current mode by number, is perfectly fine.

### Booleans

Are things loading or not, is the user logged in or not? These are typical uses of boolean values. We use booleans to express that something is activated or not. We should not confuse this with **null**, which means “not existing”. We should not use **null** in place of a boolean value. We have to use either `true` or `false`.

### Null

All values, with the exception of booleans, can also be **null**. Non-existing. You can have a non-existing object, array, string or number. It means that if we haven’t selected a mode, both the string version and number version would have the value **null**.

### Derived

When you need to derive state you can add a function to your tree. Overmind treats these functions like a **getter**, but the returned value is cached and they can also access the root state of the application. A simple example of this would be:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  title: 'My awesome title',
  upperTitle: state => state.title.toUpperCase()
}
```

{% endtab %}
{% endtabs %}

The first argument of the function is the state the derived function is attached to. A second argument is also passed and that is the root state of the application, allowing you to access whatever you would need.

{% hint style="info" %}
Even though derived state is defined as functions you consume them as plain values. You do not have to call the derived function to get the value. Derived functions can also be dynamically added.
{% endhint %}

{% hint style="info" %}
You may use a derived for all sorts of calculations. But sometimes it's better to just use a plain action to create some state than using a derived. Why? Imagine a table component having a lot of rows and columns. We assume the table component also takes care of sorting and filtering and is capable of adding new rows. Now if you solve the sorting and filtering using a derived the following could happen: User adds a new row but it is not displayed in the list because the derived immediately kicked in and filtered it out. Thats not a good user experience. Also in this case the filtering and sorting is clearly started by a simple user interaction (setting a filter value, clicking on a column,...) so why not just start an action which creates the new list of sorted and filtered keys? Also the heavy calculation is now very predictable and doesn't cause performance issues because the derived kickes in too often (Because it could have many dependencies you might didn't think of)
{% endhint %}

### Class instances

Overmind also supports using class instances as state values. Depending on your preference this can be a powerful tool to organize your logic. What classes provide is a way to co locate state and logic for changing and deriving that state. In functional programming the state and the logic is separated and it can be difficult to find a good way to organize the logic operating on that state.

It can be a good idea to think about your classes as models. They model some state.

{% tabs %}
{% tab title="overmind/models.js" %}

```javascript
class LoginForm {
  constructor() {
    this.username = ''
    this.password = ''
  }
  get isValid() {
    return Boolean(this.username && this.password)
  }
  reset() {
    this.username = ''
    this.password = ''
  }
}
```

{% endtab %}

{% tab title="overmind/state.js" %}

```javascript
import { LoginForm } from './models'

export const state = {
  loginForm: new LoginForm()
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
It is import that you do **NOT** use arrow functions on your methods. The reason is that this binds the context of the method to the instance itself, meaning that Overmind is unable to proxy access and track mutations
{% endhint %}

You can now use this instance as normal and of course create new ones.

#### Serializing class values

If you have an application that needs to serialize the state, for example to local storage or server side rendering, you can still use class instances with Overmind. By default you really do not have to do anything, but if you use **Typescript** or you choose to use **toJSON** on your classesOvermind exposes a symbol called **SERIALIZE** that you can attach to your class.

```typescript
import { SERIALIZE } from 'overmind'

class User {
  constructor() {
    this.username = ''
    this.jwt = ''
  }
  toJSON() {
    return {
      [SERIALIZE]: true,
      username: this.username
    }
  }
}
```

If you use **Typescript** you want to add **SERIALIZE** to the class itself as this will give you type safety when rehydrating the state.

```typescript
import { SERIALIZE } from 'overmind'

class User {
  [SERIALIZE] = true
  username = ''
  jwt = ''
}
```

{% hint style="info" %}
The **SERIALIZE** symbol will not be part of the actual serialization done with **JSON.stringify**
{% endhint %}

#### Rehydrating classes

The [**rehydrate**](/v23.1/api-1/rehydrate) *\*\**&#x75;tility of Overmind allows you to rehydrate state either by a list of mutations or a state object, like the following:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(state, {
    user: {
      username: 'jenny',
      jwt: '123'
    }
  })    
}
```

{% endtab %}
{% endtabs %}

Since our user is a class instance we can tell rehydrate what to do, where it is typical to give the class a static **fromJSON** method:

{% tabs %}
{% tab title="overmind/models.js" %}

```typescript
import { SERIALIZE } from 'overmind'

class User {
  [SERIALIZE]
  constructor() {
    this.username = ''
    this.jwt = ''
  }
  static fromJSON(json) {
    return Object.assign(new User(), json)
  }
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(
    state,
    {
      user: {
        username: 'jenny',
        jwt: '123'
      }
    },
    {
      user: User.fromJSON
    }
  )    
}
```

{% endtab %}
{% endtabs %}

It does not matter if the state value is a class instance, an array of class instances or a dictionary of class instances, rehydrate will understand it.

That means the following will behave as expected:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
import { User } from './models'

export const state = {
  user: null, // Can be existing class instance or null
  usersList: [], // Expecting an array of values
  usersDictionary: {} // Expecting a dictionary of values
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { rehydrate } from 'overmind'

export const updateState = ({ state }) => {
  rehydrate(
    state,
    {
      user: {
        username: 'jenny',
        jwt: '123'
      },
      usersList: [{...}, {...}],
      usersDictionary: {
        'jenny': {...},
        'bob': {...}
      }
    },
    {
      user: User.fromJSON,
      usersList: User.fromJSON,
      usersDictionary: User.fromJSON
    }
  )    
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that **rehydrate** gives you full type safety when adding the **SERIALIZE** symbol to your classes. This is a huge benefit as Typescript will yell at you when the state structure changes, related to the rehydration
{% endhint %}

### Statemachines

Very often you get into a situation where you define states as **isLoading**, **hasError** etc. Having these kinds of state can cause **impossible states**. For example:

```typescript
const state = {
  isAuthenticated: true,
  isAuthenticating: true
}
```

You can not be authenticating and be authenticated at the same time. This kind of logic very often causes bugs in applications. That is why Overmind allows you to define statemachines. It sounds complicated, but is actually very simple.

#### Defining

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
import { statemachine } from 'overmind'

export const state = {
  mode: statemachine({
    initial: 'unauthenticated',
    states: {
      unauthenticated: ['authenticating'],
      authenticating: ['unauthenticated', 'authenticated'],
      authenticated: ['unauthenticating'],
      unauthenticating: ['unauthenticated', 'authenticated']
    }
  }),
  user: null,
  error: null
}
```

{% endtab %}
{% endtabs %}

You set an **initial** state and then you create a relationship between the different states and what states they can transition into. So when **unauthenticated** is the state, only logic triggered with an **authenticating** transition will run, any other transition triggered will not run its logic.

#### Transitioning

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const login = async ({ state, effects }) => {
  return state.mode.authenticating(async () => {
    try {
      const user = await effects.api.getUser()
      return state.mode.authenticated(() => {
        state.user = user
      })
    } catch (error) {
      return state.mode.unauthenticated(() => {
        state.error = error
      })    
    }
  })
}

export const logout = async ({ state, effects }) => {
  return state.mode.unauthenticating(async () => {
    try {
      await effects.api.logout()
      return state.mode.unauthenticated()
    } catch (error) {
      return state.mode.authenticated(() => {
        state.error = error
      })    
    }
  })
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
There are two important rules for predictable transitions:

1. The transition should be **returned** if the logic or logic runs asynchronously. This is the same as with actions in general
2. Only **synchronous** transitions can mutate the state, any async mutation will throw an error
   {% endhint %}

What is important to realize here is that our logic is separated into **allowable** transitions. That means when we are waiting for the user on **line 4** and some other logic has changed the state to **unauthenticated** in the meantime, the user will not be set, as the **authenticated** transition is now not possible. This is what state machines do. They group logic into states that are allowed to run, preventing invalid logic to run.

#### Current state

The current state is accessed, related to this example, by:

```typescript
state.mode.current
```

#### Exit

It is also possible to run logic when a transition exits. An example of this is for example if a transition sets up a subscription. This subscription can be disposed when the transition is exited.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const login = async ({ state, effects }) => {
  return state.mode.authenticating(async () => {
    try {
      const user = await effects.api.getUser()
      let disposeSubscription
      state.mode.authenticated(
        () => {
          disposeSubscription = effects.api.subscribeNotifications()
          state.user = user
        },
        () => {
          disposeSubscription()
        }
      )
    } catch (error) {
      state.mode.unauthenticated(() => {
        state.error = error
      })    
    }
  })
}
```

{% endtab %}
{% endtabs %}

#### Reset

You can reset the state of a statemachine, which also runs the exit of the current transition:

```typescript
state.mode.reset()
```

## References

When you add objects and arrays to your state tree, they are labeled with an “address” in the tree. That means if you try to add the same object or array in multiple spots in the tree you will get an error, as they can not have multiple addresses. Typically this indicates that you’d rather want to create a reference to an existing object or array.

So this is an example of how you would **not** want to do it:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  users: {},
  currentUser: null
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
export const setUser = ({ state }, id) => {
  state.currentUser = state.users[id]
}
```

{% endtab %}
{% endtabs %}

You’d rather have a reference to the user id, and for example use a **getter** to grab the actual user:

{% tabs %}
{% tab title="overmind/state.js" %}

```typescript
export const state = {
  users: {},
  currentUserId: null,
  get currentUser(this) {
    return this.users[this.currentUserId]
  } 
}
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
export const setUser = ({ state }, id) => {
  state.currentUserId = id
}
```

{% endtab %}
{% endtabs %}

## Exposing the state

We define the state of the application in **state** files. For example, the top level state could be defined as:

{% tabs %}
{% tab title="overmind/state.js" %}

```javascript
export const state = {
  isLoading: false,
  user: null
}
```

{% endtab %}
{% endtabs %}

To expose the state on the instance you can follow this recommended pattern:

{% tabs %}
{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'

export const config = {
  state
}
```

{% endtab %}

{% tab title="index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
For scalability you can define **namespaces** for multiple configurations. Read more about that in [Structuring the app](/v23.1/core/structuring-the-app)
{% endhint %}

## Summary

This short guide gave you some insight into how we think about state and what state really is in an application. There is more to learn about these values and how to use them to describe the application. Please move on to other guides to learn more.


# Actions

Overmind has a concept of an **action**. An action is just a function where the first argument is injected. This first argument is called the **context** and it holds the state of the application, whatever effects you have defined and references to the other actions.

You define actions under the **actions** key of your application configuration.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction = (context) => {

}
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import * as actions from './actions'

export const config = {
  actions
}
```

{% endtab %}
{% endtabs %}

## Using the context

The context has three parts: **state**, **effects** and **actions**. Typically you destructure the context to access these pieces directly:

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const myAction = ({ state, effects, actions }) => {

}
```

{% endtab %}
{% endtabs %}

When you point to either of these you will always point to the “top of the application. That means if you use namespaces or other nested structures the context is always the root context of the application.

{% hint style="info" %}
The reason Overmind only has a root context is because having isolated contexts/domains creates more harm than good. Specifically when you develop your application it is very difficult to know exactly how the domains of your application will look like and what state, actions and effects belong together. By only having a root context you can always point to any domain from any other domain allowing you to easily manage cross-domain logic, not having to refactor every time your domain model breaks.
{% endhint %}

## Passing values

When you call actions you can pass a single value. This value appears as the second argument, after the context.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction = ({ state, effects, actions }, value) => {

}
```

{% endtab %}
{% endtabs %}

When you call an action from an action you do so by using the **actions** passed on the context, as this is the evaluated action that can be called.

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const myAction = ({ state, effects, actions }) => {
  actions.myOtherAction('foo')
}

export const myOtherAction = ({ state, effects, actions }, value) {

}
```

{% endtab %}
{% endtabs %}

## Organizing actions

Some of your actions will be called from the outside, publicly, maybe from a component. Other actions are only used internally, either being passed to an effect or just holding some piece of logic you want to reuse.&#x20;

There are two conventions to choose from:

### Namespace

{% tabs %}
{% tab title="overmind/internalActions.js" %}

```typescript
export const internalActionA = ({ state, effects, actions }, value) {}

export const internalActionB = async ({ state, effects, actions }) {}
```

{% endtab %}

{% tab title="overmind/actions.ts" %}

```typescript
import { Action } from 'overmind'
import * as internalActions from './internalActions'

export const internal = internalActions

export const myAction: Action = ({ state, effects, actions }) => {
  actions.internal.internalActionA('foo')
  actions.internal.internalActionB()
}
```

{% endtab %}
{% endtabs %}

### Underscore

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const myAction: Action = ({ state, effects, actions }) => {
  actions.internal._internalActionA('foo')
  actions.internal._internalActionB()
}

export const _internalActionA = ({ state, effects, actions }, value) {}

export const _internalActionB = async ({ state, effects, actions }) {}
```

{% endtab %}
{% endtabs %}

## Summary

The action in Overmind is a powerful concept. It allows you to define and organize logic that always has access to the core components of your application. State, effects and actions.


# Effects

Developing applications is not only about managing state, but also managing side effects. A typical side effect would be an HTTP request or talking to localStorage. In Overmind we just call these **effects**. There are several reasons why you would want to use effects:

1. All the code in your actions will be domain specific, no low level generic APIs
2. Your actions will have less code and you avoid leaking out things like URLs, types etc.
3. You decouple the underlying tool from its usage, meaning that you can replace it at any time without changing your application logic
4. You can more easily expand the functionality of an effect. For example you want to introduce caching or a base URL to an HTTP effect
5. The devtool tracks its execution
6. If you write Overmind tests, you can easily mock them
7. You can lazy-load the effect, reducing the initial payload of the app

## Exposing an existing tool

Let us just expose the [AXIOS](https://github.com/axios/axios) library as an **http** effect.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
export { default as http } from 'axios'
```

{% endtab %}

{% tab title="overmind/index.js" %}

```typescript
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'

export const config = {
  state,
  actions,
  effects
}
```

{% endtab %}
{% endtabs %}

We are just exporting the existing library from our effects file and including it in the application config. Now Overmind is aware of an **http** effect. It can track it for debugging and all actions and operators will have it injected.

Let us put it to use in an action that grabs the current user of the application.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
export const loadApp = async ({ effects, state }) => {
  state.currentUser = await effects.http.get('/user')
}
```

{% endtab %}
{% endtabs %}

That was basically it. As you can see we are exposing some low level details like the http method used and the URL. Let us follow the encouraged way of doing things and create our own **api** effect.

## Specific API

It is highly encouraged that you avoid exposing tools with their generic APIs. Rather build your own APIs that are more closely related to the domain of your application. Maybe you have an endpoint for fetching the current user. Create that as an API for your app.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
import * as axios from 'axios'

export const api = {
  getCurrentUser() {
    return axios.get<User>('/user')
  }
}
```

{% endtab %}
{% endtabs %}

Now you can see how clean your application logic becomes:

{% tabs %}
{% tab title="overmind/actions.ts" %}

```typescript
export const loadApp = async ({ effects, state }) => {
  state.currentUser = await effects.api.getCurrentUser()
}
```

{% endtab %}
{% endtabs %}

## Initializing effects

It can be a good idea to not allow your side effects to initialize when they are defined. This makes sure that they do not leak into tests or server side rendering. For example if you want to use Firebase, instead of initializing the Firebase application immediately we rather do it behind an **initialize** method:

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import * as firebase from 'firebase'

// We use IIFE to hide the private "app" variable
export const api = (() => {
  let app

  return {
    initialize() {
      app = firebase.initializeApp(...)      
    },
    async getPosts() {
      const snapshot = await app.database().ref('/posts').once('value')

      return snapshot.val()
    }
  }
})()
```

{% endtab %}
{% endtabs %}

We are doing two things here:

1. We use an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) to create a scoped internal variable to be used for that specific effect
2. We have created an **initialize** method which we can call from the Overmind **onInitialize** action, which runs when the Overmind instance is created

Example of initializing the effect:

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ effects }) => {
  effects.api.initialize()
  state.posts = await effects.api.getPosts()
}
```

{% endtab %}
{% endtabs %}

## Effects and state

Typically you explicitly communicate with effects from actions, by calling methods. But sometimes you need effects to know about the state of the application, or maybe some internal state in the effect should be exposed on your application state. Again we can take advantage of an **initialize** method on the effect:

{% tabs %}
{% tab title="overmind/effects.js" %}

```javascript
// We use an IIFE to isolate some variables
export const socket = (() => {
  _options
  _ws
  return {
    initialize(options) {
      _options = options
      _ws = new WebSocket('ws://...')
      _ws.onclose = () => options.onStatusChange('close')
      _ws.onopen = () => options.onStatusChange('open')
      _ws.addEventListener(
        'message',
        (event) => options.onMessage(event.data)
      )
    },
    send(type, data) {
      _ws.postMessage({
        type,
        data,
        token: _options.getToken()
      })
    }
  }
})()
```

{% endtab %}

{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ state, effects, actions }) => {
  effects.socket.initialize({
    onMessage: actions.onMessage,
    onStatusChange: actions.onSocketStatusChange,
    getToken() {
      return state.token
    }
  })
}
```

{% endtab %}
{% endtabs %}

Here we are passing in actions that can be triggered by the effect to expose internal state and/or other information that you want to manage.

## Lazy effects

You can also lazily load your effects in the **initialize** method. Let us say we wanted to load Firebase and its API on demand, or maybe just split out the code to make our app start faster.

{% tabs %}
{% tab title="overmind/effects.js" %}

```typescript
export const api = (() => {
  let app

  return {
    async initialize() {
      const firebase = await import('firebase')

      app = firebase.initializeApp(...)
    },
    async getPosts() {
      const snapshot = await app.database().ref('/posts').once('value')

      return snapshot.val()
    }
  }
})()
```

{% endtab %}
{% endtabs %}

In our initialize() we would just have to wait for the initialization to finish before using the API:

{% tabs %}
{% tab title="overmind/onInitialize.js" %}

```typescript
export const onInitialize = async ({ effects }) => {
  await effects.api.initialize()
  state.posts = await effects.api.getPosts()
}
```

{% endtab %}
{% endtabs %}

We could have been even bolder here making our effect download its dependency related to using any of its methods. Imagine for example the **firebase** library downloading when you run a **login** method on the effect.

## Configurable effect

By defining a class we can improve testability, allow using environment variables and even change out the actual implementation.

{% tabs %}
{% tab title="overmind/effects.ts" %}

```typescript
import axios from 'axios'

export class Api {
  private baseUrl
  private request
  constructor (baseUrl, request) {
    this.baseUrl = baseUrl
    this.request = request
  }
  getCurrentUser()  {
    return this.request.get(`${this.baseUrl}/user`)
  }
}

export const api = new Api(IS_PRODUCTION ? '/api/v1' : 'http://localhost:4321', axios)
```

{% endtab %}
{% endtabs %}

We export an instance of our **Api** to the application. This allows us to also create instances in isolation for testing purposes, making sure our Api class works as we expect.

## Summary

Importing side effects directly into your code should be considered bad practice. If you think about it from an application standpoint it is kinda weird that it runs HTTP verb methods with a URL string passed in. It is better to create an abstraction around it to make your code more consistent with the domain, and by doing so also improve maintainability.


# Operators

You get very far building your application with straightforward imperative actions. This is typically how we learn programming and is arguably close to how we think about the world. But this approach can cause you to overload your actions with imperative code, making them more difficult to read and especially reuse pieces of logic. As the complexity of your application increases you will find benefits to doing some of your logic, or maybe all your logic, in a functional style.

Let us look at a concrete example of how messy an imperative approach would be compared to a functional approach.

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
let debounce
export const search = ({ state, effects }, event) => {
  state.query = event.currentTarget.value

  if (query.length < 3) return

  if (debounce) clearTimeout(debounce)

  debounce = setTimeout(async () => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false

    debounce = null
  }, 200)
}
```

{% endtab %}
{% endtabs %}

What we see here is an action trying to express a search. We only want to search when the length of the query is more than 2 characters and we only want to trigger the search when the user has not changed the query for 200 milliseconds.

If we were to do this in a functional style it would look more like this:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import { pipe, debounce, mutate, filter } from 'overmind'

export const search = pipe(
  mutate(({ state }, value) => {
    state.query = value
  }),
  filter(({ state }) => state.query.length > 2),
  debounce(200),
  mutate(({ state, effects }) => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false
  })
)
```

{% endtab %}
{% endtabs %}

As you can see our action is described more declaratively. We could have moved each individual piece of logic, each operator, into a different file. All these operators could now be reused in other action compositions.

## Structuring operators

You will typically rely on an **operators** file where all your composable pieces live. Inside your **actions** file you expose the operators and compose them together using **pipe** and other *composing* operators. This approach ensures:

1. Each operator is defined separately and in isolation
2. The action composed of operators is defined with the other actions
3. The action composed of operators is declarative (no inline operators with logic)

Let us look at how the operators in the search example could have been implemented:

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {filter, mutate } from 'overmind'

export const setQuery = () =>
  mutate(function setQuery({ state }, query) {
    state.query = query
  })

export const lengthGreaterThan = (length) =>
  filter(function lengthGreaterThan(_, value) {
    return value.length > length
  })

export const getSearchResult = () => 
  mutate(async function getSearchResult({ state, effects }, query) {
    state.isSearching = true
    state.searchResult = await effects.api.search(query)
    state.isSearching = false
  })
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that we give all the actual operator functions the same name as the exported variable that creates it. The reason is that this name is picked up by the devtools and gives you more insight into how your code runs.
{% endhint %}

You might wonder why we define the operators as functions that we call. We do that for the following reasons:

1. It ensures that each composition using the operator has a unique instance of that operator. For most operators this does not matter, but for others like **debounce** it actually matters.
2. Some operators require options, like the **lengthGreaterThan** operator we created above. Defining all operators as functions just makes things more consistent.
3. If you were to create an operator that is composed of other operators you can safely do so without thinking about the order of definition in the *operators* file. The reason being that the operator is lazily created
4. With Typescript it opens up to partial and generic typed operators. Read more about this in the [Typescript](/v23.1/core/typescript) guide

Now, you might feel that we are just adding complexity here. An additional file with more syntax. But clean and maintainable code is not about less syntax. It is about structure, predictability and reusability. What we achieve with this functional approach is a super readable abstraction in our *actions* file. There is no logic there, just references to logic. In our *operators* file each piece of logic is defined in isolation with very little logic.

## Calling operators

You typically compose the different operators together with **pipe** and **parallel** in the *actions* file, but any operator can actually be exposed as an action. With the search example:

{% tabs %}
{% tab title="overmind/actions.js" %}

```typescript
import {pipe, debounce, mutate, filter } from 'overmind'

export const search = pipe(
  mutate(({ state }, value) => {
    state.query = value
  }),
  filter(({ state }) => state.query.length > 2),
  debounce(200),
  mutate(({ state, effects }) => {
    state.isSearching = true
    state.searchResult = await effects.api.search(state.query)
    state.isSearching = false
  })
)
```

{% endtab %}
{% endtabs %}

You would call this action like any other:

```typescript
overmind.actions.search("something")
```

## Inputs and Outputs

To produce new values throughout your pipe you can use the **map** operator. It will put whatever value you return from it on the pipe for the next operator to consume.

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {map, mutate } from 'overmind'

export const toNumber = () =>
  map(function toNumber(_, value) { 
    return Number(value)
  })

export const setValue = () =>
  mutate(function setValue({ state}, value) {
    state.value = value
  })
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import {pipe } from 'overmind'
import * as o from './operators'

export const onValueChange = pipe(
  o.toNumber(),
  o.setValue()
)
```

{% endtab %}
{% endtabs %}

## Custom operators

The operators concept of Overmind is based on the [OP-OP SPEC](https://github.com/christianalfoni/op-op-spec), which allows for endless possibilities in functional composition. But since Overmind does not only pass values through these operators, but also the context where you can change state, run effects etc., we want to simplify how you can create your own operators. The added benefit of this is that the operators you create are also tracked in the devtools.

### toUpperCase <a href="#create-custom-operators-touppercase" id="create-custom-operators-touppercase"></a>

Let us create an operator that simply uppercases the string value passed through. This could easily have been done using the **map** operator, but for educational purposes let us see how we can create our very own operator.

{% tabs %}
{% tab title="overmind/operators.js" %}

```typescript
import {createOperator, mutate } from 'overmind'

export const toUpperCase = () => {
  return createOperator('toUpperCase', '', (err, context, value, next) => {
    if (err) next(err, value)
    else next(null, value.toUpperCase())
  })
}

export const setTitle = mutate(({ state }, title) => {
  state.title = title
})
```

{% endtab %}

{% tab title="overmind/actions.js" %}

```typescript
import { pipe } from 'overmind'
import { toUpperCase, setTitle } from './operators'

export const setUpperCaseTitle = pipe(
  toUpperCase(),
  setTitle
)
```

{% endtab %}
{% endtabs %}

We first create a function that returns an operator when we call it. We pass this operator a **name**, an optional **description** and the callback that is executed when the operator runs. This operator might receive an **error**, that you can handle if you want to. It also receives the **context**, the current **value** and a function called **next**.

In this example we did not use the **context** because we are not going to look at any state, run effects etc. We just wanted to change the value passed through. All operators need to handle the **error** in some way. In this case we just pass it along to the next operator by calling **next** with the error as the first argument and the current value as the second. When there is no error it means we can manage our value and we do so by calling **next** again, but passing **null** as the first argument, as there is no error. And the second argument is the new **value**.

### operations <a href="#create-custom-operators-operations" id="create-custom-operators-operations"></a>

You might want to run some logic related to your operator. Typically this is done by giving a callback. You can provide this callback whatever information you want, even handle its return value. So for example the **map** operator is implemented like this:

```typescript
import { createOperator } from 'overmind'

export function map(operation) {
  return createOperator(
    'map',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else next(null, operation(context, value))
    }
  )
}
```

### mutations <a href="#create-custom-operators-mutations" id="create-custom-operators-mutations"></a>

You can also create operators that have the ability to mutate the state, it is just a different factory **createMutationFactory**. This is how the **mutate** operator is implemented:

```typescript
import { createMutationOperator } from 'overmind'

export function mutate(operation) {
  return createMutationOperator(
    'mutate',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else {
        operation(context, value)
        next(null, value)
      }
    }
  )
}
```

### paths <a href="#create-custom-operators-paths" id="create-custom-operators-paths"></a>

You can even manage paths in your operator. This is how the **when** operator is implemented:

```typescript
import { createOperator } from 'overmind'

export function when(operation, paths) {
  return createOperator(
    'when',
    operation.name,
    (err, context, value, next) => {
      if (err) next(err, value)
      else if (operation(context, value))
        next(null, value, {
          name: 'true',
          operator: paths.true,
        })
      else
        next(null, value, {
          name: 'false',
          operator: paths.false,
        })
    }
  )
}
```

### aborting <a href="#create-custom-operators-aborting" id="create-custom-operators-aborting"></a>

Some operators want to prevent further execution. That is also possible to implement, as seen here with the **filter** operator:

```typescript
import { createOperator } from 'overmind'

export function filter(operation) {
  return createOperator(
    'filter',
    operation.name,
    (err, context, value, next, final) => {
      if (err) next(err, value)
      else if (operation(context, value)) next(null, value)
      else final(null, value)
    }
  )
}
```

The **final** argument bypasses any other operators.


# Statecharts

Just like [OPERATORS](/v23.1/core/going-functional) is a declarative abstraction over plain actions, **statecharts** is a declarative abstraction over an Overmind configuration of **state** and **actions**. That means you will define your charts by:

```typescript
const configWithStatechart = statechart(config, chart)
```

There are several benefits to using statecharts:

1. You will have a declarative description of what actions should be available in certain states of the application
2. Less bugs because an invalid action will not be executed if called
3. You will be able to implement and test an interaction flow without building the user interface for it
4. Your state definition is cleaned up as your **isLoading** types of state is no longer needed
5. You have a tool to do “top down” implementation instead of “bottom up”

You can basically think of a statechart as a way of limiting what actions are available to be executed in certain states of the application. This concept is very old and was originally used to design machines where the user was exposed to all points of interaction, all buttons and switches, at any time. Statecharts would help make sure that at certain states certain buttons and switches would not operate.

A simple example of this is a Walkman. When the Walkman is in a **playing** state you should not be able to hit the **eject** button. On the web this might seem unnecessary as points of interaction is dynamic. We simply hide and/or disable buttons. But this is the exact problem. It is fragile. It is fragile because the UI implementation itself is all you depend on to prevent logic from running when it should not. A statechart is a much more resiliant way to ensure what logic can actually run in any given state.

In Overmind we talk about these statechart states as **transition states**.

## Defining a statechart

Let us imagine that we have a login flow. This login flow has 4 different **transition states**:

1. **LOGIN**. We are at the point where the user inserts a username and password
2. **AUTHENTICATING**. The user has submitted
3. **AUTHENTICATED**. The user has successfully logged in
4. **ERROR**. Something wrong happened

Let us do this properly and design this flow “top down”:

{% tabs %}
{% tab title="overmind/login/index.js" %}

```typescript
import { statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const loginChart = {
  initial: 'LOGIN',
  states: {
    LOGIN: {
      on: {
        changeUsername: null,
        changePassword: null,
        login: 'AUTHENTICATING'
      }
    },
    AUTHENTICATING: {
      on: {
        resolveUser: 'AUTHENTICATED',
        rejectUser: 'ERROR'
      }
    },
    AUTHENTICATED: {
      on: {
        logout: 'LOGIN'
      }
    },
    ERROR: {
      on: {
        tryAgain: 'LOGIN'
      }
    }
  }
}

export default statechart(config, loginChart)
```

{% endtab %}
{% endtabs %}

As you can see we have defined what transition states our login flow can be in and what actions we want available to us in each transition state. If the action points to **null** it means we stay in the same transition state. If it points to an other transition state, the execution of that action will cause that transition to occur.

Since our initial state is **LOGIN**, a call to actions defined in the other transition states would simply be ignored.

{% hint style="info" %}
You might expect actions to throw an error if they are called, but not allowed to do so. This is not the case with statecharts. During development you will get a warning when this happens, but in production absolutely nothing happens. Hitting a submit button multiple times might be perfectly okay, but after the first submit the chart moves to a new state, preventing any further execution of logic on the following submits.
{% endhint %}

## Transitions

If you are familiar with the concept of statemachines you might ask the question: *“Where are the transitions?”*. In Overmind we use actions to define transitions instead of having explicit transition types. That means you think about statecharts in Overmind as:

```
TRANSITION STATE -> ACTION -> NEW TRANSITION STATE
```

as opposed to:

```
TRANSITION STATE -> TRANSITION TYPE -> { NEW TRANSITION STATE, ACTION }
```

This approach has three benefits:

1. It is more explicit in the definition that a transition state configures what actions are available
2. When typing your application the actions already has a typed input, which would not be possible with a generic **transition** action
3. It is simpler concept both in code and for your brain

What to take notice of is that the **action** causing the transition is run before the transition actually happens. That means the action runs in the context of the current transition state and any synchronous calls to another action will obey its rules. If the action does something asynchronous, like doing an HTTP request, the transition will be performed and the asynchronous logic will run in the context of the new transition state.

```typescript
const myTransitionAction = async ({ actions }) => {
  // I am still in the current transition state
  actions.someOtherAction()

  await Promise.resolve()

  // I am in the new transition state
  actions.someOtherAction()
}
```

## Nested statecharts

With a more complicated UI we can create nested statecharts. An example of this would be a workspace UI with different tabs. You only want to allow certain actions when the related tab is active. Let us explore an example:

{% tabs %}
{% tab title="overmind/dashboard/index.js" %}

```typescript
import { statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const issuesChart = {
  initial: 'LOADING',
  states: {
    LOADING: {
      entry: 'fetchIssues',
      exit: 'abortFetchIssues',
      on: {
        resolveIssues: 'LIST',
        rejectIssues: 'ERROR'
      }
    },
    LIST: {
      on: {
        toggleIssueCompleted: null
      }
    },
    ERROR: {
      on: {
        retry: 'LOADING'
      }
    },
  }
}

const projectsChart = {
  initial: 'LOADING',
  states: {
    LOADING: {
      entry: 'fetchProjects',
      exit: 'abortFetchProjects',
      on: {
        resolveIssues: 'LIST',
        rejectIssues: 'ERROR'
      }
    },
    LIST: {
      on: {
        expandAttendees: null
      }
    },
    ERROR: {
      on: {
        retry: 'LOADING'
      }
    },
  }
}

const dashboardChart = {
  initial: 'ISSUES',
  states: {
    ISSUES: {
      on: {
        openProjects: 'PROJECTS'
      },
      chart: issuesChart
    },
    PROJECTS: {
      on: {
        openIssues: 'ISSUES'
      },
      chart: projectsChart
    }
  }
}

export default statechart(config, dashboardChart)
```

{% endtab %}
{% endtabs %}

What to take notice of in this example is that all chart states has its own **chart** property, which allows them to be nested. The nested charts has access to the same actions and state as the parent chart.

In this example we also took advantage of the **entry** and **exit** hooks of a transition state. These also points to actions. When a transition is made into the transition state, the **entry** will run. This behavior is nested. When an **exit** hook exists and a transition is made away from the transition state, it will also run. This behavior is also nested of course.

## Parallel statecharts

It is also possible to define your charts in a parallel manner. You do this by simply using an object of keys where the key represents an ID of the chart. The **chart** property on a transition state allows the same. Either a single chart or an object of multiple charts where the key represents an ID of the chart.

```typescript
export default statechart(config, {
  issues: issuesChart,
  projects: projectsChart
})
```

## Conditions

In our chart above we let the user log in even though there is no **username** or **password**. That seems a bit silly. In statecharts you can define conditions. These conditions receives the state of the configuration and returns true or false.

{% tabs %}
{% tab title="overmind/login/index.js" %}

```typescript
import {statechart } from 'overmind/config'
import * as actions from './actions'
import { state } from './state'

const config = {
  state,
  actions
}

const loginChart = {
  initial: 'LOGIN',
  states: {
    LOGIN: {
      on: {
        changeUsername: null,
        changePassword: null,
        login: {
          target: 'AUTHENTICATING',
          condition: state => Boolean(state.username && state.password)
        }
      }
    },
    ...
  }
}

export default statechart(config, loginChart)
```

{% endtab %}
{% endtabs %}

Now the **login** action can only be executed when there is a username and password inserted, causing a transition to the new transition state.

## State

Our initial state defined for this configuration is:

{% tabs %}
{% tab title="overmind/login/state.js" %}

```typescript
export const state = {
  username: '',
  password: '',
  user: null,
  authenticationError: null
}
```

{% endtab %}
{% endtabs %}

As you can see we have no state indicating that we have received an error, like **hasError**. We do not have **isLoggingIn** either. There is no reason, because we have our transition states. That means the configuration is populated with some additional state by the statechart. It will actually look like this:

```typescript
{
  username: '',
  password: '',
  user: null,
  authenticationError: null,
  states: [['CHART', 'LOGIN']],
  actions: {
    changeUsername: true,
    changePassword: true,
    login: false,
    logout: false,
    tryAgain: false
  }
}
```

The **states** state is the current transition states. It is defined as an array of arrays. This indicates that we can have parallel and nested charts. The **CHART** symbol in the array indicates that you have defined an immediate chart. If you rather defined parallel charts you would define your own ids.

The **actions** state is a derived state. That means it automatically updates based on the current state of the chart. This is helpful for your UI implementation. It can use it to disable buttons etc. to help the user understand when certain actions are possible.

### Identifying states <a href="#statecharts-identifying-states" id="statecharts-identifying-states"></a>

There is also a third derived state called **matches**. This derived state returns a function that allows you to figure out what state you are in. This is also the API you use in your components to identify the state of your application:[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/guide/statecharts/matches.ts.ts)

```typescript
state.login.matches({
  LOGIN: true
})
```

You can also do more complex matches related to parallel and nested charts:[EDIT ON GITHUB](https://github.com/cerebral/overmind/edit/next/packages/overmind-website/examples/guide/statecharts/matches_multiple.ts.ts)

```typescript
// Nested
const isSearching = state.dashboard.matches({
  LIST: {
    search: {
      SEARCHING: true
    }
  }
})

// Parallel
const isDownloadingAndUploading = state.files.matches({
  download: {
    LOADING: true
  },
  upload: {
    LOADING: true
  }
})

// Complex match
const isOnlyDownloading = state.files.matches({
  download: {
    LOADING: true
  },
  upload: {
    LOADING: false
  }
})
```

### Actions <a href="#statecharts-actions" id="statecharts-actions"></a>

Our actions are defined something like:

{% tabs %}
{% tab title="overmind/login/actions.js" %}

```typescript
export const changeUsername = ({ state }, username) => {
  state.login.username = username
}

export const changePassword = ({ state }, password) => {
  state.login.password = password
}

export const login = ({ state, actions, effects }) => {
  try {
    const user = await effects.api.login(state.username, state.password)
    actions.login.resolveUser(user)
  } catch (error) {
    actions.login.rejectUser(error)
  }
}

export const resolveUser = ({ state }, user) => {
  state.login.user = user
}

export const rejectUser = ({ state }, error) => {
  state.login.authenticationError = error.message
}

export const logout = ({ effects }) => {
  effects.api.logout()
}

export const tryAgain = () => {}
```

{% endtab %}
{% endtabs %}

What to take notice of here is that with traditional Overmind we would most likely just set the **user** or the **authenticationError** directly in the **login** action. That is not the case with statcharts because our actions are the triggers for transitions. That means whenever we want to deal with transitions we create an action for it, even completely empty actions like **tryAgain**. This simplifies our chart definition and also we avoid having a generic **transition** action that would not be typed in TypeScript.

Now these two charts would operate individually. This is also the case for the **chart** property on the states of a chart.

## Devtools

The Overmind devtools understands statecharts. That means you are able to get an overview of available statecharts and even manipulate them directly in the devtools.

![](/files/-LyeAtF5_zJ45kWzFpgY)

You will see what transition states and actions are available, and active, within each of them. You can click any active action to select it and click again to execute, or insert at payload at the top before execution.

## Summary

The point of statecharts in Overmind is to give you an abstraction over your configuration that ensures the actions can only be run in certain states. Just like operators you can choose where you want to use it. Maybe only one namespace needs a statechart, or maybe you prefer using it on all of them. The devtools has its own visualizer for the charts, which allows you to implement and test them without implementing any UI.w


# Server Side Rendering

Some projects require you to render your application on the server. There are different reasons to do this, like search engine optimizations, general optimizations and even browser support. What this means for state management is that you want to expose a version of your state on the server and render the components with that state. But that is not all, you also want to **hydrate** the changed state and pass it to the client with the HTML so that it can **rehydrate** and make sure that when the client renders initially, it renders the same UI.

## Preparing the project

When doing server-side rendering the configuration of your application will be shared by the client and the server. That means you need to structure your app to make that possible. There is really not much you need to do.

{% tabs %}
{% tab title="overmind/index.ts" %}

```typescript
import { IConfig } from 'overmind'
import { state } from './state'

export const config = {
  state
}

declare module 'overmind' {
  interface Config extends IConfig<typeof config> {}
}
```

{% endtab %}

{% tab title="index.ts" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
```

{% endtab %}
{% endtabs %}

Here we only export the configuration from the main Overmind file. The instantiation rather happens where we prepare the application on the client side. That means we can now safely import the configuration also on the server.

## Preparing effects

The effects will also be shared with the server. Typically this is not an issue, but you should be careful about creating effects that run logic when they are defined. You might also consider lazy-loading effects so that you avoid loading them on the server at all. You can read more about them in [EFFECTS](/v23.1/core/running-side-effects).

## Rendering on the server

When you render your application on the server you will have to create an instance of Overmind designed for running on the server. On this instance you can change the state and provide it to your components for rendering. When the components have rendered you can **hydrate** the changes and pass them along to the client so that you can **rehydrate**.

{% hint style="info" %}
Overmind does not hydrate the state, but the mutations you performed. That means it minimizes the payload passed over the wire.
{% endhint %}

The following shows a very simple example using an [EXPRESS](https://expressjs.com/) middleware to return a server side rendered version of your app.

{% tabs %}
{% tab title="server/routePosts.ts" %}

```typescript
import { createOvermindSSR } from 'overmind'
import { config } from '../client/overmind'
import db from './db'

export default async (req, res) => {
  const overmind = createOvermindSSR(config)

  overmind.state.currentPage = 'posts'
  overmind.state.posts = await db.getPosts()

  const html = renderToString(
    // Whatever implementation your view layer provides
  )

  res.send(`
<html>
  <body>
    <div id="app">${html}</div>
    <script>
      window.__OVERMIND_MUTATIONS = ${JSON.stringify(overmind.hydrate())}
    </script>
    <script src="/scripts/app.js"></script>
  </body>
</html>
`)
}
```

{% endtab %}
{% endtabs %}

## Rehydrate on the client

On the client you just want to make sure that your Overmind instance rehydrates the mutations performed on the server so that when the client renders, it does so with the same state. The **onInitialize** hook of Overmind is the perfect spot to do this.

{% tabs %}
{% tab title="overmind/onInitialize.ts" %}

```typescript
import { OnInitialize, rehydrate } from 'overmind'

export const onInitialize: OnInitialize = ({ state }) => {
  const mutations = window.__OVERMIND_MUTATIONS

  rehydrate(state, mutations)
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
If you are using state first routing, make sure you prevent the router from firing off the initial route, as this is not needed.
{% endhint %}

## OnInitialize

The `onInitialized` action does not run on the server. The reason is that it is considered a side effect you might not want to run, so we do not force it. If you do want to run an action as Overmind fires up both on the client and the server you can rather create a custom action for it.

{% tabs %}
{% tab title="overmind/actions.js" %}

```javascript
export const initialize = () => {
  // Whatever...
}
```

{% endtab %}

{% tab title="client/index.js" %}

```typescript
import { createOvermind } from 'overmind'
import { config } from './overmind'

const overmind = createOvermind(config)
overmind.actions.initialize()
```

{% endtab %}

{% tab title="server/index.js" %}

```javascript
import { createOvermindSSR } from 'overmind'
import { config } from '../client/overmind'

export default async (req, res) => {
  const overmind = createOvermindSSR(config)
  await overmind.actions.initialize()

  const html = renderToString(
    // Whatever implementation your view layer provides
  )

  res.send(`
<html>
  <body>
    <div id="app">${html}</div>
    <script>
      window.__OVERMIND_MUTATIONS = ${JSON.stringify(overmind.hydrate())}
    </script>
    <script src="/scripts/app.js"></script>
  </body>
</html>
`)
}
```

{% endtab %}
{% endtabs %}




---

[Next Page](/llms-full.txt/1)

