cerebral / overmind

Overmind - Frictionless state management
https://overmindjs.org
MIT License
1.58k stars 95 forks source link

[BUG] State mutation error #531

Closed Arsen777 closed 3 years ago

Arsen777 commented 3 years ago

[

Screen Shot 2021-07-14 at 18 42 49

](url)

"overmind": "^27.0.0", "overmind-react": "^28.0.0" "npm": "6.13.4", "Mac Os": "Big Sur, 11.4", "Chrome": "Version 91.0.4472.114 (Official Build) (x86_64)"

Hello,

I discovered a bug while updating store with callback in action. Async/Await works fine, but callback version does not work. You had similar issues, which are closed now https://github.com/cerebral/overmind/issues/307 https://github.com/cerebral/overmind/issues/300

Also I have figured out that the issue exists after "overmind-react": "^19.0.1",

jmattheis commented 3 years ago

State mutations aren't allowed outside overmind actions. With setTimeout overmind cannot know where these changes originated.

You can use an async function:

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

export const login = async ({ state }) => {
  await sleep(1000);
  state.user = {};
};

or use overmind operators

import { pipe, wait } from 'overmind'

export const login = pipe(
  wait(1000),
  ({ state }) => {
    state.user = {};
  }
)
grandevel commented 3 years ago

Another way to do this, which might be better for tracking in the devtools, is to have two actions -

export const login = async ({ actions }) => { setTimeout(() => { actions.resetUser() }, 1000) };

export const resetUser = async ({ state }) => { state.user = {}; };

Then it is clear when both actions fire, and which action is doing what. Also good for reuse - because the principal of what each action is doing is clear.

But as with anything, you should also consider quite why you want a delay after login - if you are waiting for some event, it's usually better to tap it and respond to the event rather than an arbitrary delay.

christianalfoni commented 3 years ago

Closing this for now as both answers are correct 😄