rescript-lang/rescript-react

Passing an async function to useCallback with more than one parameter results in a non-async function

lozlow opened this issue · 4 comments

Hi there,

I noticed that when passing this async function:

let onSubmit = React.useCallback(async (_a, _b) => {
    await Promise.resolve()
})

it results in the following JS code which does not compile as the function is not async:

var onSubmit = React.useCallback(function (_a) {
      return function (_b) {
        return await Promise.resolve(undefined);
      };
    });

I think useCallback takes functions with 1 argument.
That said, that code should not be generated.
Could you try to define the callback function separately, instead of inlining it, and see what the generated code looks like. That would be a useful test to determine the scope of what's going on.

Thanks @cristianoc, I wasn't aware of that restriction wrt useCallback but extracting the function does produce valid JS:

let cb = async (_a, _b) => {
  await Promise.resolve()
}
let onSubmit = React.useCallback(cb)

compiles to:

async function cb(_a, _b) {
  return await Promise.resolve(undefined);
}

var onSubmit = React.useCallback(function (param) {
      return function (param$1) {
        return cb(param, param$1);
      };
    });

Thanks. So the issue is contained to async functions auto curried when inlined. Would you move this issue to the compiler repo?

For the specific example, useCallback2 seems like the way to go.