You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: pages/docs/manual/v9.0.0/newcomer-examples.mdx
+98Lines changed: 98 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -132,3 +132,101 @@ function greetByName(possiblyNullName) {
132
132
</CodeTab>
133
133
134
134
This check compiles to `possiblyNullName == null` in JS, so checks for the presence of `null` or `undefined`.
135
+
136
+
## Modeling reducers
137
+
138
+
A reducer is a function that accepts in some state and an action and returns a new state. In ReScript, you can model the state and the action as separate types.
139
+
140
+
### Modeling state
141
+
142
+
For modeling the state type, it's best to use a record over an object type:
When you need to store a dictionary of values, try using the `Belt.Map` type. The `Belt` library contains safe methods for working with immutable data structures (they won't throw errors):
166
+
167
+
<CodeTablabels={["ReScript", "JS Output"]}>
168
+
169
+
```res example
170
+
open Belt
171
+
172
+
type todo = {
173
+
id: string,
174
+
name: string,
175
+
completed: bool
176
+
}
177
+
178
+
type state = {
179
+
todos: Map.String.t<todo>
180
+
}
181
+
182
+
// Example of a function that adds a todo. We use the `Belt.Map.String.set`
183
+
// function to add the todo to the todos map.
184
+
let addTodo = (state: state, todo: todo): state => {
For smaller reducers (reducers with only a few sub-functions), you can use a variant for your action type. You can use a `switch` statement to pattern match on the different action types. Here's an example of a reducer for a simple counter:
201
+
202
+
```res example
203
+
type state = {
204
+
count: int
205
+
}
206
+
207
+
type action =
208
+
| Increment
209
+
| Decrement
210
+
211
+
let reducer = (state: state, action: action): state => {
0 commit comments