Asynchronous function in the hooks of smartActions

Hi !
I have a “Users” collection on which I can execute different smartActions. I want to add a new Enum type field in one of my single actions, which would contain specific data from the selected user (ids).

{
      name: 'KYC Review Simple',
      type: 'single',
      fields: [
        {
          field: 'ID Card',
          isRequired: true,
          description: 'The copy of the ID card of the user',
          type: 'File',
        },
        {
          field: 'treezorId',
          isRequired: true,
          description: '',
          type: 'Enum',
          enums: []
        }
      ],
      hooks: {
        load: async ({ fields }, user) => {
          user = await UserObject.findById(user._id);
          fields.treezorId.enums = user.getTreezorUserIds();
          return fields;
        }
      }
    },

Expected behavior

Visually, I should have a select field with the user’s ids as options.

Actual behavior

I have the select field, but nothing as options. Either my user is undefined or my fields is undefined.
When I write my hook like that (see below), it works.

hooks: {
        load: ({ fields }) => {
          fields.treezorId.enums = ["a", "b"];
          return fields;
        }
      }

But when I write my function as an asynchronous call, it doesn’t work at all. In the same code file, there’s many asynchronous calls which work.

Failure Logs

[forest] 🌳🌳🌳  Error in smart action hook: Cannot read property '_id' of undefined
{
  "stack": "TypeError: Cannot read property '_id' of undefined

Context

forest-express-mongoose Version: 7.6.0

Is there something I’m doing wrong ?

Hey @SpookyUmi, and welcome to our community :wave:

Since your smart action is related to your Users collection, you should be able to retrieve your user._id directly within the smart action context, like so:

        load: async ({ fields, record }) => {
          console.log(record); // Should return the record currently selected for the smart action
          return fields;
        }

If I’m not wrong,

        load: async ({ fields, record: user }) => {
          user = await UserObject.findById(user._id);
          fields.treezorId.enums = user.getTreezorUserIds();
          return fields;
        }

may work out of the box.

Let me know if that helps

1 Like

It works well ! Thanks a lot !

1 Like