Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update atom state in reaction #87

Open
c01nd01r opened this issue Apr 9, 2024 · 1 comment
Open

Update atom state in reaction #87

c01nd01r opened this issue Apr 9, 2024 · 1 comment

Comments

@c01nd01r
Copy link
Contributor

c01nd01r commented Apr 9, 2024

Hi!
I've come across a situation where it's necessary to change the state of an atom within a reaction.

type AsyncResource = {
  hasError: Signal<boolean>;
  error: Signal<string>;
}

type NotifyStore = {
  messages: Signal<string[]>
  addMessage: (message) => void
}

const notify: NotifyStore = useNotify();
const asyncResource: AsyncResource = useAsyncResource(() => fetch('/error-response'));

useEffect(() => react('add message', () => {
  if (asyncResource.hasError.value) { 
    notify.addMessage(asyncResource.error.value)
  }
}), [])

When a reaction is triggered, the notify.messages atom gets updated, and execution fails with the error 'cannot change atoms during reaction cycle'.
From what I understand, this behavior corresponds to this test:

it('can not set atom values directly yet', () => {
const a = atom('', 1)
const r = reactor('', () => {
if (a.value < +Infinity) {
a.update((a) => a + 1)
}
})
expect(() => r.start()).toThrowErrorMatchingInlineSnapshot(
`"cannot change atoms during reaction cycle"`
)
})

Are there any workarounds for this situation?

@muhajirdev
Copy link

I was having a similar issue. Finally ended up just not using signia for this one particular case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants