Hendry Lim
Hendry Lim

Reputation: 1974

formik access initialValues in onSubmit handler for comparison with values

I have an edit form which uses Formik. I need to upload a new image if the picture string has changed. I need to compare the initialValues of the picture field vs the values of the picture field to determine whether to call the fileUpload function to upload a picture and return the string uri

How can i access the initialValues in my onSubmit handler in order to do this comparison. I have been searching online and found an article on this topic, however, the author is using redux and recompose. In my case, I am using graphql and am not using any state management libraries

Is it possible to still do such a comparison without a state management library? n how can i access initialValues inside my onSubmit handler?

formProps has both initialValues and values. submitProps only have values but doesn't have initialValues which I need to make a comparison if the field has been changed by the user

<Formik
  initialValues={{
    ...getMusicById,
  }}
  onSubmit={(values, bag, ...submitProps) => {
    console.log("@onSubmit ", values, bag, submitProps);
    const {
      session: { me }
    } = this.props;
    this._handleSubmit(values, bag, me);
  }}
  validationSchema={formValidateSchema}
  render={({ isValid, isSubmitting, ...formProps }) => {
    console.log("@formProps ", formProps);
    return (
      <React.Fragment>
        <Form>

Upvotes: 2

Views: 5152

Answers (1)

xadm
xadm

Reputation: 8418

Is it possible to still do such a comparison without a state management library? n how can i access initialValues inside my onSubmit handler?

Not directly - simplicity of ready components (<Formik/>) always has drawbacks.

You can use any state management method and pass values for initialValues as props.

In article <Formik/> is embeded into <FooForm/> enhanced with HOC's. Values are stored in redux and passed as props into <Formik />

You can use simple class component and it's state (or props) to be passed down as initialValues. Submit handler defined in the same component (passed as prop, too) will have access to data/object in this.state. Of course you can use hooks - useState for this in functional component.

You can use withFormik HOC - props.initialValues should be available.

Upvotes: 3

Related Questions