formik form reset on action dispatch

464 views Asked by At

is there any possible ways to reset the form right after I dispatch the action ?

something like:

const formik = useFormik({
  onSubmit: (values, {resetForm}) => {
    dispatch(action.register(values)) //some action creator with axios.post request

    if (isRegistred) { resetForm() }  //isRegistred - value from Selector which changes on dispatch to true

  }
})
const register = (user) => (dispatch) => {
  return axios
    .post(`${API_URL}/user/create/`, {
      first_name: user.firstName,
      second_name: user.secondName,
      date_birth: user.dateBirth,
      phone_number: user.phoneNumber,
      gender: user.gender,
      email: user.email,
      city: user.city,
      username: user.username,
      password1: user.password1,
      password2: user.password2
    })
    .then((response) => {
      dispatch({ type: '@USER/register-success', isRegistred: response.data?.success })
    })
    .catch((error) => {
      dispatch({ type: '@USER/register-error', error: error?.response?.data?.errors })
    })
}

export const action = { register }

I know, it's kinda silly, because it's changing value right after. Maybe there any other approaches ?

1

There are 1 answers

0
4rmr3d1 On BEST ANSWER

if someone intrested, i just pass the resetForm from onSubmit formik to action creator.

  const formik = useFormik({
    initialValues,
    validationSchema,
    onSubmit: (values, { resetForm }) => {
      dispatch(userActions.register(values, { resetForm }))
    },
    validateOnChange: false,
    validateOnBlur: true
  })
const register = (user, { resetForm }) => (dispatch) => {
  return axios
    .post(`${API_URL}/user/create/`, {
      first_name: user.firstName,
      second_name: user.secondName,
      date_birth: user.dateBirth,
      phone_number: user.phoneNumber,
      gender: user.gender,
      email: user.email,
      city: user.city,
      username: user.username,
      password1: user.password1,
      password2: user.password2
    })
    .then((response) => {
      dispatch({ type: '@USER/register-request' })

      if (response.data?.success) {
        dispatch({ type: '@USER/register-success', isRegistred: response.data?.success })
        resetForm()
      }
    })
    .catch((error) => {
      dispatch({ type: '@USER/register-error', error: error?.response?.data?.errors })
    })
}