How to use "Yup" library to calculate the sum of all elements in an array and check with a number?

Viewed 160

There is an object data

{
  products: [{id: 1, sum: 10}, {id: 2, sum: 50}],
  total: 60
}

My "yup" circuit looks

const schema = yup.object().shape({
  products: yup.array().of(yup.object().shape({
    id: yup.number().required(),
    sum: yup.number().required(),
  }))
  .min(1)
  .required(),
  total: yup.number().min(10).required(),
});

I want to get rid of my functions

const checkSum = (data) => {
  let productsTotal = 0;
  const {products, total} = data;
  products.forEach((product) => {
    productsTotal += product.sum;
  });

  if (productsTotal !== total ) return false;

  return true;
}

Can you tell me this can be done with "yup"?

0 Answers
Related