Skip to content

Commit 5de1319

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

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

computed-values.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,81 @@
11
# Computed values
22

3+
Sometimes you want to computed a value based on some input and the current state of the application. That is why we have the concept of a **computed**.
4+
5+
{% code-tabs %}
6+
{% code-tabs-item title="app/computed.js" %}
7+
```javascript
8+
import { computed } from 'overmind'
9+
10+
export const usersList = computed(config => state => {
11+
const users = state.users
12+
13+
return users
14+
.filter(user => user.isAwesome === config.isAwesome)
15+
.sort((userA, userB) => userA[config.sortField] < userB[config.sortField])
16+
.slice(config.startIndex, config.endIndex)
17+
})
18+
```
19+
{% endcode-tabs-item %}
20+
21+
{% code-tabs-item title="app/computed.ts" %}
22+
```typescript
23+
import { computed } from 'overmind'
24+
import { State } from './state'
25+
26+
export type UsersListConfig {
27+
isAweome: boolean
28+
sortField: string
29+
startIndex: number
30+
endIndex: number
31+
}
32+
33+
export const usersList = computed((config: UsersListConfig) => (state: State) => {
34+
const users = state.users
35+
36+
return users
37+
.filter(user => user.isAwesome === config.isAwesome)
38+
.sort((userA, userB) => userA[config.sortField] < userB[config.sortField])
39+
.slice(config.startIndex, config.endIndex)
40+
})
41+
```
42+
{% endcode-tabs-item %}
43+
{% endcode-tabs %}
44+
45+
You attach computed to the state, just like **derived** state:
46+
47+
{% code-tabs %}
48+
{% code-tabs-item title="app/state.js" %}
49+
```javascript
50+
import * as computed from './computed'
51+
52+
export default {
53+
users: [],
54+
usersList: computed.usersList
55+
}
56+
```
57+
{% endcode-tabs-item %}
58+
59+
{% code-tabs-item title="app/state.ts" %}
60+
```typescript
61+
import * as computed, { UsersListConfig } from './computed'
62+
63+
export type User = {
64+
name: string
65+
}
66+
67+
export type State = {
68+
users: User[]
69+
usersList: (config: UsersListConfig) => User[]
70+
}
71+
72+
export default {
73+
users: [],
74+
usersList: computed.usersList
75+
}
76+
```
77+
{% endcode-tabs-item %}
78+
{% endcode-tabs %}
79+
80+
You use a computed by calling it and giving it an argument, like **config** in this example.
81+

0 commit comments

Comments
 (0)