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.
1
reaction(
2
// Access and return some state to react to
3
(state) => state.foo,
4
5
// Do something with the returned value
6
(foo) => {},
7
8
{
9
// If you return an object or array from the state you can set this to true.
10
// The reaction will run when any nested changes occur as well
11
nested: false,
12
13
// Runs the reaction immediately
14
immediate: false
15
}
16
)
Copied!
There are two points of setting up reactions in Overmind.

onInitializeOvermind

The onInitializeOvermind action 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.
overmind/actions.js
1
export const onInitializeOvermind = ({ effects }, instance) => {
2
instance.reaction(
3
({ todos }) => todos,
4
(todos) => effects.storage.saveTodos(todos),
5
{
6
nested: true
7
}
8
)
9
}
Copied!

components

With components you typically use reactions to manipulate DOM elements or other UI related imperative libraries.
React
Angular
Vue
1
import * as React from 'react'
2
import { useOvermind } from '../overmind'
3
4
const App = () => {
5
const { reaction } = useOvermind()
6
7
React.useEffect(() => reaction(
8
({ currentPage }) => currentPage,
9
() => {
10
document.querySelector('#page').scrollTop = 0
11
}
12
))
13
14
return <div id="page"></div>
15
}
16
17
export default App
Copied!
1
import { Component } from '@angular/core';
2
import { Store } from '../overmind'
3
4
@Component({
5
selector: 'app-root',
6
template: `
7
<div id="page"></div>
8
`
9
})
10
export class App {
11
constructor(private store: Store) {}
12
ngOnInit() {
13
this.store.reaction(
14
({ currentPage }) => currentPage,
15
() => {
16
document.querySelector('#page').scrollTop = 0
17
}
18
)
19
}
20
}
Copied!
1
<template>
2
<div id="page"></div>
3
</template>
4
<script>
5
export default {
6
mounted() {
7
this.overmind.reaction(
8
({ currentPage }) => currentPage,
9
() => {
10
document.querySelector('#page').scrollTop = 0
11
}
12
)
13
}
14
}
15
</script>
Copied!
Last modified 5mo ago