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

Want to obtain the new state synchronously - can't? #20

Closed
deanrad opened this issue Sep 22, 2019 · 3 comments
Closed

Want to obtain the new state synchronously - can't? #20

deanrad opened this issue Sep 22, 2019 · 3 comments

Comments

@deanrad
Copy link

deanrad commented Sep 22, 2019

Given an initialized useMethods

  const [ productReviewState, stateChangers ] = useMethods(...);

And an updater like the following:

      updateAnswer: ({ questionId, value, isValid = true }) => {
        state.answers[questionId] = value;
        state.answerValidity[questionId] = isValid;
      }

When I run an effect hook, how can I synchronously have the value of the answerValidity subkey of productReviewState?

      console.log(
        `answerValidity[${questionId}]`,
        productReviewState.answerValidity[questionId]
      );
      stateChangers.updateAnswer({ questionId, value, isValid });
      console.log(
        `answerValidity[${questionId}]`,
        productReviewState.answerValidity[questionId]
      );

The second console log never reflects the updated value. I suppose this is just immutability at work, but I'd at least like a way to "requery" for the current value. TIA.

@dalevink
Copy link

As you've suspected, this is by design, as useMethods implements useReducer.

Here's a similar question/answer posted for useReducer:

console.log(state) is a side effect. Side effects belong to useEffect hook:

https://stackoverflow.com/questions/55559307/react-hooks-usereducer-wait-for-reducer-to-finish-before-triggering-a-functio

@pelotom
Copy link
Owner

pelotom commented Sep 26, 2019

It's not possible to synchronously see what the new state will be after calling a state-changing function. There's not even afaik a way to asynchronously wait and see what the new state will be (see facebook/react#15344).

@deanrad
Copy link
Author

deanrad commented Sep 27, 2019

Great updates @dalevink and @pelotom. I've learned soo much about hooks and such after getting going with use-methods. Thank you!

@deanrad deanrad closed this as completed Sep 27, 2019
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

3 participants