Sunday, 11 September 2022

How do I submit form data after another hook is set?

When a user submits a form, I have to show a modal asking them to connect if they haven't yet. On success, the modal sets the user data in a hook, and then I continue with the submission flow.

So there are 2 conditions to submit:

  1. User submits form (clicks button)
  2. User data is set

I solved it reactively, using an effect:

useEffect(() => {
  async function nestedAsync() {
    if (userData && pendingSubmitIntent) {
      pendingSubmitIntent(false);
      await submit(
        formData, // simplified - this is actually several hooks
        userData
      );
    }
  }
  nestedAsync();
}, [pendingSubmitIntent, userData]);

And the submit click handler:

setPendingSubmitIntent(true);
if (!userData) {
  setShowConnectModal(true);
}

The modal is in the component:

{setShowConnectModal && (
  <ConnectModal
    setUserData={setUserData}
  />
)}

This actually works, but I'm getting a warning that I'm not declaring formData in the dependencies array. I can't do this, because otherwise the effect will be called when editing the inputs and that's not correct. The effect has to be called only when submitting.

And this warning makes me think that there's something fundamentally wrong with this approach. A state machine comes to mind, but I feel that it should be simpler. Any ideas?



from How do I submit form data after another hook is set?

No comments:

Post a Comment