3

I want to use ES2017 async and await syntax for returning a promise from a validation function in Redux Form. My current function looks like this:

export const asyncValidateUsername = values => {
  return async () => {
    if (!values.username) return;
    const data = await axios.get(`/validate/${values.username}`);
    if (data) {
      throw { username: `Username ${values.username} is already taken.`};
    } else {
      return { username: 'Valid username.' }
    }
  }
}

And then I wrap this function with lodash's debounce function:

const asyncValidate = _.debounce(asyncValidateUsername, 200);

I am getting the following error with this code:

Uncaught Error: asyncValidate function passed to reduxForm must return a promise

I thought async functions implicitly return a promise. Is there a bug in my code or is this an error on Redux Form's part? Any help would be appreciated.

Nic Bonetto
  • 543
  • 1
  • 8
  • 20

3 Answers3

0

Asycn functions returns a promise as you said, but your top level function is not an async function, it returns an async function. I'm not so familiar with Redux Form but you can try like that:

export const asyncValidateUsername = async values => {
    if (!values.username) return;
    const data = await axios.get(`/validate/${values.username}`);
    if (data) {
      throw { username: `Username ${values.username} is already taken.`};
    } else {
      return { username: 'Valid username.' }
    }
}
devserkan
  • 16,870
  • 4
  • 31
  • 47
0

It would seem that since the _.debouce is wrapping it now it returns that value of the debounce, which would seem to not be a promisey value.

This answer talks about debounce returning a promise...

Debounce function implemented with promises

Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
0

You can prevent this error by adding asyncBlurFields: [] like

MyAwesomeForm = reduxForm({
  ...
  asyncBlurFields: [] 
})(MyAwesomeForm)
David Buck
  • 3,752
  • 35
  • 31
  • 35