Skip to content
Advertisement

Can’t pass proper value in form, react

I have created a form in react using Formiz. But it’s not sending right value.

Here is a working CodeSandbox: https://codesandbox.io/s/formiz-pricing-wizard-forked-fcnsn?file=/src/fields/fieldradio.js

Currently it is sending me this value:

wrong value

But it should send me this value:

right value

I already tried changing step1.js from this:

const transformOptions = (options) =>
  options.map(({ subCategory, price, radioImage }, i) => ({
    label: <span>{subCategory}</span>,
    id: `${subCategory}-${i}`,
    value: `${price}`,
    image: radioImage
  }));

To this:

const transformOptions = (options) =>
  options.map(({ subCategory, price, radioImage }, i) => ({
    label: <span>{subCategory}</span>,
    id: `${subCategory}-${i}`,
    value: `${subCategory} - ${price}`,
    image: radioImage
  }));

It sends me the right values but totalPrice function in MyForm.js stops working:

const totalPrice = React.useMemo(() => {
    return categories.reduce(
      (total, c) =>
        total + (myForm.values[c] ? parseInt(myForm.values[c], 10) : 0),
      0
    );
  }, [myForm.values]);

Will anyone please help me to fix it? Because I’ve been trying to find a solution for hours but still couldn’t find one and can’t wrap my head around what’s going wrong!

Advertisement

Answer

Since you modified value from ${price} to ${subCategory} - ${price} now your totalPrice is broken because in myForm.values[c] there is no more just the price but the subCategory also.

To solve this it’s just necessary fix your totalPrice in this way:

  const totalPrice = React.useMemo(() => {

    return categories.reduce(
      (total, c) =>
        total +
        (myForm.values[c]?.split("-")[1]
          ? parseInt(myForm.values[c]?.split("-")[1], 10)
          : 0),
      0
    );
  }, [myForm.values]);

I replaced myForm.values[c] with myForm.values[c]?.split("-")[1] in order to “clean” value from subCategory part and leave just price.

Here your codesandbox modified.

Advertisement