YUP/Formik带去反跳的异步验证

人气:235 发布:2023-01-03 标签: reactjs formik yup

问题描述

如何将取消退回应用于下面的异步验证(code from Yup's github)?

let asyncJimmySchema = string().test(
  'is-jimmy',
  '${path} is not Jimmy',
  async (value) => (await fetch('/is-jimmy/' + value)).responseText === 'true',
});

推荐答案

您可以使用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(validationNameFunction, ASYNC_VALIDATION_TIMEOUT_IN_MS);

然后在验证方案中:

let asyncJimmySchema = string().test(
  'is-jimmy',
  '${path} is not Jimmy',
  value => new Promise(resolve => validationDebounced(value, resolve)),
});

23