Skip to content

Commit 4355c31

Browse files
christianalfonigitbook-bot
authored andcommitted
GitBook: [master] one page modified
1 parent b60149f commit 4355c31

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

core/defining-state.md

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,10 @@ export const state = {
113113
{% endtab %}
114114
{% endtabs %}
115115

116+
{% hint style="warning" %}
117+
It is import that you do **NOT** use arrow functions on your methods. The reason is that this binds the context of the method to the instance itself, meaning that Overmind is unable to proxy access and allow you to do tracked mutations
118+
{% endhint %}
119+
116120
You can now use this instance as normal and of course create new ones.
117121

118122
{% hint style="info" %}
@@ -384,11 +388,11 @@ export const login = async ({ state, effects }) => {
384388
return state.mode.authenticating(async () => {
385389
try {
386390
const user = await effects.api.getUser()
387-
state.mode.authenticated(() => {
391+
return state.mode.authenticated(() => {
388392
state.user = user
389393
})
390394
} catch (error) {
391-
state.mode.unauthenticated(() => {
395+
return state.mode.unauthenticated(() => {
392396
state.error = error
393397
})
394398
}
@@ -399,9 +403,9 @@ export const logout = async ({ state, effects }) => {
399403
return state.mode.unauthenticating(async () => {
400404
try {
401405
await effects.api.logout()
402-
state.mode.unauthenticated()
406+
return state.mode.unauthenticated()
403407
} catch (error) {
404-
state.mode.authenticated(() => {
408+
return state.mode.authenticated(() => {
405409
state.error = error
406410
})
407411
}
@@ -411,8 +415,11 @@ export const logout = async ({ state, effects }) => {
411415
{% endtab %}
412416
{% endtabs %}
413417

414-
{% hint style="info" %}
415-
If your transition runs asynchronously you should return the transition to ensure that the action execution is tracked
418+
{% hint style="warning" %}
419+
There are two important rules for predictable transitions:
420+
421+
1. The transition should be **returned** if the logic or logic runs asynchronously. This is the same as with actions in general
422+
2. Only **synchronous** transitions can mutate the state, any async mutation will throw an error
416423
{% endhint %}
417424

418425
What is important to realize here is that our logic is separated into **allowable** transitions. That means when we are waiting for the user on **line 4** and some other logic has changed the state to **unauthenticated** in the meantime, the user will not be set, as the **authenticated** transition is now not possible. This is what state machines do. They group logic into states that are allowed to run, preventing invalid logic to run.

0 commit comments

Comments
 (0)