Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup / Formik async validation with debounce

How can debounce be applied to the async validation below (code from Yup's github) ?

let asyncJimmySchema = string().test(
  'is-jimmy',
  '${path} is not Jimmy',
  async (value) => (await fetch('/is-jimmy/' + value)).responseText === 'true',
});
like image 353
le0 Avatar asked Oct 27 '19 05:10

le0


2 Answers

You can implement it by your self by using lodash.debounce:

import { debounce } from "lodash";

// .....

const ASYNC_VALIDATION_TIMEOUT_IN_MS = 1000;

const validationFunction = async (value, resolve) => {
  try {
    const response = await fetch('/is-jimmy/' + value);
    resolve(response.responseText === 'true');
  } catch (error) {
    resolve(false);
  }
};

const validationDebounced = debounce(validationFunction, ASYNC_VALIDATION_TIMEOUT_IN_MS);

Then in the validation scheme:

let asyncJimmySchema = string().test(
  'is-jimmy',
  '${path} is not Jimmy',
  value => new Promise(resolve => validationDebounced(value, resolve)),
});
like image 60
Raúl Otaño Avatar answered Nov 11 '22 18:11

Raúl Otaño


I think this should work. It's copying the solution from just-debounce-it but returning a Promise right away, which is what Yup expects.

const asyncDebouncer = (fn, wait, callFirst) => {
  var timeout;
  return function() {
    return new Promise(async (resolve) => {
      if (!wait) {
        const result = await fn.apply(this, arguments);
        resolve(result);
      }

      var context = this;
      var args = arguments;
      var callNow = callFirst && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(async function() {
        timeout = null;
        if (!callNow) {
          const result = await fn.apply(context, args);
          resolve(result);
        }
      }, wait);

      if (callNow) {
        const result = await fn.apply(this, arguments);
        resolve(result);
      }
    });
  };
};

let asyncJimmySchema = string().test(
  'is-jimmy',
  '${path} is not Jimmy',
  asyncDebouncer((value) => (await fetch('/is-jimmy/' + value)).responseText === 'true', 400),
});
like image 20
christo8989 Avatar answered Nov 11 '22 16:11

christo8989