Skip to content

Commit e7b07c5

Browse files
christianalfonigitbook-bot
authored andcommitted
GitBook: [master] one page modified
1 parent 76ed7fa commit e7b07c5

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

derived-state.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,46 @@
11
# Derived state
22

3+
Sometimes state is not a value you insert, but a value calculated based on other state. This is what we call **derived** state. An example of this would be a list of the completed todos. You could filter out these todos inside a component, but the logic does not really belong there. It belongs with the rest of your application logic. What we want to make sure of is that this calculation only runs when it actually needs to, meaning when any of the existing completed todos becomes uncompleted or todos are added or removed from the list.
4+
5+
{% code-tabs %}
6+
{% code-tabs-item title="app/state.js" %}
7+
```javascript
8+
import { derived } from 'overmind'
9+
10+
export default {
11+
todos: [],
12+
completedTodos: derived(
13+
state => state.todos.filter(todo => todo.completed)
14+
)
15+
}
16+
```
17+
{% endcode-tabs-item %}
18+
19+
{% code-tabs-item title="app/state.ts" %}
20+
```typescript
21+
import { derived } from 'overmind'
22+
23+
type Todo = {
24+
title: string
25+
completed: boolean
26+
}
27+
28+
type State = {
29+
todos: Todo[]
30+
completedTodos: Todo[]
31+
}
32+
33+
const state: State = {
34+
todos: [],
35+
completedTodos: derived(
36+
(state: State) => state.todos.filter(todo => todo.completed)
37+
)
38+
}
39+
40+
export default state
41+
```
42+
{% endcode-tabs-item %}
43+
{% endcode-tabs %}
44+
45+
Even though you express the value as a function, it can be accessed as normal both in actions and components: `state.completedTodos`
46+

0 commit comments

Comments
 (0)