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
If you want to use external sources of events (e.g. a timer), you can use a `subscription`. With this those events can be processed by our `update` handler.
371
+
372
+
Let's define a `Model` and a `Message`:
373
+
374
+
```ts
375
+
type Message =
376
+
| { name: "timer", date: Date };
377
+
378
+
interfaceModel {
379
+
date: Date,
380
+
}
381
+
382
+
const Msg = {
383
+
timer: (date:Date):Message=> ({ name: "timer", date }),
384
+
};
385
+
```
386
+
387
+
Now we define the `init` function and the `update` object:
388
+
389
+
```ts
390
+
const cmd =createCmd<Message>();
391
+
392
+
function init (props:Props):InitResult<Model, Message> {
393
+
return [{
394
+
date: newDate(),
395
+
}];
396
+
}
397
+
398
+
const update:UpdateMap<Props, Model, Message> = {
399
+
timer ({ date }) {
400
+
return [{ date }];
401
+
},
402
+
};
403
+
```
404
+
405
+
Then we write our `subscription` function:
406
+
407
+
```ts
408
+
function subscription (model:Model):SubscriptionResult<Message> {
You can define and aggregate multiple subscriptions with a call to `cmd.batch(...)`.
426
+
427
+
### Cleanup subscriptions
428
+
429
+
In the solution above `setInterval` will trigger events even if the component is removed from the DOM. To cleanup subscriptions, we can return a `destructor` function from the subscription the same as in the `useEffect` hook.
430
+
431
+
Let's rewrite our `subscription` function:
432
+
433
+
```ts
434
+
function subscription (model:Model):SubscriptionResult<Message> {
Here we save the return value of `setInterval` and clear that interval in the returned `destructor` function.
450
+
365
451
## Setup
366
452
367
453
**react-elmish** works without a setup. But if you want to use logging or some middleware, you can setup **react-elmish** at the start of your program.
0 commit comments