react-use-form-state icon indicating copy to clipboard operation
react-use-form-state copied to clipboard

Function to reset pristine

Open gitcatrat opened this issue 3 years ago • 2 comments

Situation:

  • some kind of update form is rendered (e.g user profile update page)
  • user hits submit but request is not made because form is pristine
  • user changes an input or two
  • user hits submit, form is not pristine anymore and request is made
  • user hits submit again after response, request is made again

If user submits their changes and it gets acknowledged by server, form is considered pristine again in my book.

Tried something like this but I'm not sure if correct reference reaches form state. Noticed some issues.

function submitForm() {
    // if values are the same, there's
    // no point to make a request
    if (form.isPristine()) return;

    updateEntityOnServer({
      variables: form.values
    }).then(response => {
      // make all values pristine again
      Object.keys(form.pristine).forEach(key => {
        form.pristine[key] = true;
      });
      // other stuff...
    });
  }

Would be great to have something like this:

form.resetPristine();

gitcatrat avatar Jan 02 '21 07:01 gitcatrat

Hey, I've got a similar problem.

  const [
    currentUserUpdate,
    { loading, errors }
  ] = useCurrentUserUpdateMutation()

  const initial = {
    firstName: user.firstName,
    lastName: user.lastName,
    email: user.email
  }
  const [
    { values, isPristine },
    { email, password, text, raw, checkbox }
  ] = useFormState<State>(initial)

  // After calling `currentUserUpdate` which causes change of `initial`. 

  // I would expect the form to be pristine again because current values match the new initial state.
  console.log(isEqual(initial, values)) // true

  // But isProstine() / formState.pristine behave differently.
  console.log(isPristine()) // false

Maybe I'm not using the API correctly.

Calling resetPristine() after successful mutation would fix this.

Alternatively, changing initial should reflect in changed initial state for useFormState, but it doesn't. I noticed in the code that useFormState has initialState and initialValues. initial makes its way into initialState, but intialValues never change. pristine compares values from initialValues. Why do we need both initalState and initialValues?

martinliptak avatar Jan 21 '21 10:01 martinliptak

initialState should be allowed to update, because my alternative is to unmount the component and the mount it again, which is not desirable.

yanickrochon avatar Dec 01 '22 17:12 yanickrochon