Formik: async mapPropsToValues doesn't seem to work

Created on 23 Nov 2018  路  9Comments  路  Source: formium/formik

馃悰 Bug report

Current Behavior

mapPropsToValues: async () => {
  const test = await someFunction()
  return {
    example: test || ''
  }
},

returns example as undefined.

Additional context

I'm using it on React native, here's the full snippet

withFormik({
  mapPropsToValues: async () => {
    const linkCopied = await Clipboard.getString()
    return {
      link: linkCopied || 'test'
    }
  },
  validationSchema: ({ intl: { formatMessage } }) => Yup.object().shape({
    link: Yup.string().url(formatMessage({ id: 'invalid_url' }))
      .required(formatMessage({ id: 'required_field'
    })),
  }),
  handleSubmit({ link }, {
    props: { navigation, generate }, setErrors, setSubmitting, resetForm
  }) {
    generate(link, setSubmitting, navigation, setErrors, resetForm)
  }
})

Your environment

| Software | Version(s) |
| ---------------- | ---------- |
| Formik | 1.3.0
| React | 16.5.0
| TypeScript |
| Browser |
| npm/Yarn | Yarn 1.12.1
| Operating System | macOS Mojave

All 9 comments

It does not support async behavior. This is not a bug.

Oh, I see, thanks!

So, what is the recommended way of solving this?

Since I'm using recompose I solved my issue using the lifecycle HOC like so:

lifecycle({
  async componentDidMount() {
    const linkCopied = await Clipboard.getString()
    this.setState({ linkCopied })
  }
}),
withFormik({
  enableReinitialize: true,
  mapPropsToValues: ({ linkCopied }) => ({
    link: linkCopied || 'test'
  }),
  validationSchema: ({ intl: { formatMessage } }) => Yup.object().shape({
    link: Yup.string().url(formatMessage({ id: 'invalid_url' }))
      .required(formatMessage({ id: 'required_field'
    })),
  }),
  handleSubmit({ link }, {
    props: { navigation, generate }, setErrors, setSubmitting, resetForm
  }) {
    generate(link, setSubmitting, navigation, setErrors, resetForm)
  }
})

I simply added enableReinitialize: true, even though that might case some unexpected results later on.

This issue was about using async/await within formik and not enabling props reinitialization.

Only way to solve it is use component based, I don't know how to use withFormik proper way to get values from async await to fill data in input area (edit data) and proper way to handle state related to form but not state in form like state redirect

This would be a great feature... useful for getting data from an api in an edit form for example

You can get your data from a parent component and pass them as props to your form component

Was this page helpful?
0 / 5 - 0 ratings

Related issues

najisawas picture najisawas  路  3Comments

jordantrainor picture jordantrainor  路  3Comments

dearcodes picture dearcodes  路  3Comments

jaredpalmer picture jaredpalmer  路  3Comments

emartini picture emartini  路  3Comments