Home > Blockchain >  why in array undefined?
why in array undefined?

Time:12-26

mycode

https://codesandbox.io/s/focused-thompson-w7v9c2?file=/index.tsx

<Formik
        initialValues={initialValues}
        onSubmit={async (values) => {
          await new Promise((r) => setTimeout(r, 500));
          // alert(JSON.stringify(values, null, 2));
          values.product.map((item, i: number) => {
            let qty: number[] = [];
            console.log(i   "-------qty------");
            console.log(item.qty);
            console.log(i   "-------price------");
            console.log(item.price);

            if (item.qty! && item.price!) {
              qty[i] = item.qty * item.price;

              console.log(qty);
            }
              const result = qty.reduce((sum, number) => {
                return sum   number;
              }, 0);
              setSum(result)
            console.log("-------result------");
            console.log(result);

            console.log("-------Sum------");
            console.log(sum);
            console.log("-------langth------");
            console.log(i);
          });
        }}
      >

I added the price and qty to the contiguous array. and i need price qty combined but result array [ undefined, 30] or [undefined,undefined ,40] When I add data to an array i want to record in const [sum, setSum] = useState(0)

CodePudding user response:

You are setting sum for each product, at every iteration. You may want to do some reading: reduce and map.

<Formik
        initialValues={initialValues}
        onSubmit={async (values) => {
          await new Promise((r) => setTimeout(r, 500));
          // alert(JSON.stringify(values, null, 2));
          const result = values.product.reduce((sum, p) => {
                return sum   p.qty * p.price;
              }, 0);
          setSum(result)
          
            console.log(result);

          });
        }}
      >

CodePudding user response:

your if condition is wrong. replace this

        if (item.qty! && item.price!) {

with this

        if (!item.qty && !item.price) {
  • Related