score:-1

make sure that you are not creating a new instance of the debouncer each time:

import { debounce } from 'lodash'

const isjimmy = async (value,resolve) => {
    const response = await fetch('/is-jimmy/' + value))
    resolve(response.responsetext === 'true')
}

const debounceinstance = (func,delay=1000) => {
    const funcdebounced = debounce(func,delay)
    return (newvalue) => 
        new promise(resolve => 
            funcdebounced(newvalue,resolve))
}

//bad - creates a new instance on each call
const asyncjimmyschema = string()
  .test(val=> debounceinstance(isjimmy)(val)});

//good - same instance for each call
const asyncjimmyschema = string()
  .test(debounceinstance(isjimmy))}


score:1

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),
});

score:5

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)),
});

Related Query

More Query from same tag