0

I'm following this example for dependent fields https://formik.org/docs/examples/dependent-fields

At this point

const {
    values: { taxRefundAmount },
    setFieldValue,
  } = useFormikContext()

I want to destructure values based on a certain condition like this for example

const {
    values: { props.name === 'taxRefundVATAmount' ? taxRefundAmount : taxChargeAmount },
    setFieldValue,
  } = useFormikContext()

Of course, this throws an error. Is this even possible?

Mohsin
  • 97
  • 10
  • 1
    No, you can't dynamically declare symbols. How would the interpreter know which symbols can be used below this line? – windowsill Feb 10 '22 at 19:16
  • "*Is this even possible?*" no. Destructuring is not magic. It''s just a shorter way to do something that's already possible as `const taxRefundAmount = useFormikContext().values.taxRefundAmount`. That's pretty much it - saves you typing the final property twice and the full path on the right hand side. You can also do multiple at once, rather than declaring each variable and repeating the RHS. What you're trying to do [is conditionally create a variable](https://stackoverflow.com/questions/5187530/variable-variables-in-javascript) which I'd heavily advise against. – VLAZ Feb 10 '22 at 19:17
  • 1
    Sounds like an [XY-Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) if you need a different code flow for `props.name === 'taxRefundVATAmount'` then why don't you do that with an `if(props.name === 'taxRefundVATAmount') { } else { }`? – t.niese Feb 10 '22 at 19:29

1 Answers1

0

You could do something like this, get the bits you need and do it the simple way without the spread operator:

const formikContext = useFormikContext();
const setFieldValue = formikContext.setFieldValue ;
const values = props.name === 'taxRefundVATAmount'
               ? formikContext.values.taxRefundAmount
               : formikContext.values.taxChargeAmount;

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • If `const { values: { taxRefundAmount }, setFieldValue, } = useFormikContext()` is correct, then `useFormikContext` returns an object with the property `values` that is assigned to the variable `taxRefundAmount`. So both of you examples wouldn't be correct? – t.niese Feb 10 '22 at 21:11
  • @t.niese — Good catch! I missed the extra layer of nesting (teach me to try to do 2 things at once). Thanks! Answer amended. – Nicholas Carey Feb 11 '22 at 00:46
  • That still does not look right. Based on the given code of the OP `useFormikContext().values` should be either assigned to `taxRefundAmount` or to `taxChargeAmount`. In your changed code you assigned to `value`, and `taxRefundAmount`/`taxChargeAmount` are defined nowhere in your code. – t.niese Feb 11 '22 at 07:38