Code step

The Code Step allows you to write JavaScript code that will be run when the step is executed with Async/Await syntax support. The common use cases for the Code Step are transforming and mapping of the data, validation, preparing data before sending to a database or API, etc.

You can use UI Bakery variable {{data}} to access a result of the previous step, or {{ui.input.value}} to access a value of a specific UI Component.

Additionally, custom JS libraries can also be connected to utilize their functionality within your code.

Built-in variables

The following built-in variables are available:

// result of the previous step
return {{data}};

// error response of the previous step
return {{error}};

// incoming action params, passed in by components,
// the Execution/Loop action steps or when calling the action from the code
return {{params}};

// the response of the request, if the Code step follows an HTTP API step
return {{res}};

While {{data}} and {{error}} are specific to a particular step, {{params}} is available in all steps.

Using variables

// use `{{data.<key>}}` to access a specific key
return {{data.name}};

// to access the first element of the array
return {{data[0]}};

// to access the `name` key of the first element
return {{data[0].name}};

Optional chaining and default values

If at some point a variable's value is null or undefined, an optional chaining operator ?. can be used to access a specific key.

For example:

// if `data` is `null` or `undefined`, `name` will not produce an error
return {{data?.name}};
// if `data` is `null` or `undefined`, `name` will not produce an error
return {{data?.[0]?.name}};

If a variable is null or undefined, a default value can be provided using the nullish coaleasing ?? operator.

// the default value will be returned
return {{data?.name ?? 'default'}};

In combination with the if statement

const userRole = {{data?.role ?? 'user'}};
if (userRole === 'admin') {
  // do something
}

Data transformation

If the API returns its data in a different format than the components expect, you can use the code step to transform it. For example, a table component expects an array of objects, but the API returns an object with an items key that contains the array, you can use the following code to transform it to the desired format:

return {{data.items}};

In some cases, API may return an object with the data key inside:

return {{data.data}};

Access an inner array object and map it to a new array:

return {{data}}.map(item => {
  return {
    id: item.id,
    name: item.name.toUpperCase(),
  };
});

Add a new key to the array of objects:

return {{data}}.map(item => {
  return {
    ...item, // put all the keys from the original object
    created_at: new Date(), // add a new property
  };
});

Filter array of objects, short version:

return {{data}}.filter(item => item.id > 10);

Multiline version:

return {{data}}.filter((item) => {
  return item.id > 10;
});

Component values & methods

In the code step, you can access the values of the UI components and call their methods. For example, if you have a form component, you can access its value using {{ui.form.value}} variable.

const formValue = {{ui.form.value}};
delete formValue.password;

return formValue;

You can also call component methods, for example, {{ui.form.submit()}} will submit the form.

// ui.form.submit() can also be used without the parentheses
{{ui.form.submit()}}

Or to hide the modal, you can use {{ui.modal.close()}}:

// ui.modal.close() can also be used without the parentheses
{{ui.modal.close()}}

Merging results of multiple steps

In some cases, you may need to merge the results of multiple steps into a single object. Use {{steps.<step_name>.data}} to access the output of any previous step:

const users = {{steps.loadUsers.data}};
const orders = {{steps.loadOrders.data}};

return users.map(user => {
  const userOrders = orders
    .filter(order => order.userId === user.id);

  return {
    ...user,
    userOrders,
  };
});

Some steps, like Save to State or Show Notification, do not have a variable as they do not produce any output.

Note: step must have a name to be accessible as a variable.

Using variables inside strings

If you need to add a variable inside a string, you can do it by placing it in ${ } expression:

const name = `Hello ${ {{user.name}} }`;

Debugging errors

In case the code is failing or produces unexpected results:

  • make sure no linter errors are present in the code (exclamation mark in the left gutter);

  • check the result of the previous step (the {{data}} variable) and of the other variables (ex. {{params}});

  • comment out the code and add return {{data}}; to see if the data is in the expected format;

  • use the console.log to print the data to the console (Logs section at the bottom of the action).

// commented to test
// if ({{data}}.length > 10) {
//   return {{data}};
// }

console.log({{data}});

Use moment and lodash

Moment and lodash libraries are preloaded in the code step. You can use them to manipulate dates and other values.

Transform date to a specific format:

return {{data}}.map(item => {
  return {
    ...item, // put all the keys from the original object
    created_at: moment(item.created_at).format('MMMM Do YYYY, h:mm:ss a')
  };
});

Get deep value from an object:

return _.get({ data }, 'birth.place.country', 'n/a');

Custom validation

If you need to validate the data before submitting it to a database or an API, you can simply throw an error with a custom message:

if (!{{data.name}}) {
  throw new Error('User name is a required field');
}

This will prevent the action from executing the next steps. Alternatively, you can mark the code step as:

and use the message in the Show Notification step as {{error.message}}.

Call and merge data from other actions

Sometimes you need to call another action to get some data and merge it with the current data. For example, you have a list of users, and you want to get the list of their orders. You can use the following code to call another action and merge the result with the current data:

const orders = await {{actions.loadOrders.trigger()}};
// Note that the `async` keyword is required
return {{data}}.map(async (item) => {
  return {
    ...item,
    // user id will be passed as a {{params}} to the action
    orders: await {{actions.loadOrders.trigger(item.id)}},
};
});

Another example - load two different lists of data and merge them into one array:

const users = await {{actions.loadUsers.trigger()}};
const orders = await {{actions.loadOrders.trigger()}};

return {{users}}.map(item => {
  return {
    ...item,
    orders: orders.filter(order => order.user_id === item.id),
  };
});

Useful examples

Map data for the select component

return {{data}}.map(item => {
  return {
    label: item.name,
    value: item.id,
  };
});

Add "Not selected" option at the beginning of the array:

const items = {{data}}.map(item => {
  return {
    label: item.name,
    value: item.id,
  };
});

items.unshift({ value: null, label: 'Not Selected' });

return items;

Add color to the select dropdown items:

const colors = ['success', 'warning', 'danger', 'info', 'basic', 'control', 'primary'];
const items = {{data}}.map((item, index) => {
  const color = colors[index] ? colors[index] : 0;
  return { value: item.productLine, label: item.productLine, color };
});

items.unshift({ value: null, label: 'Not Selected' });
return items;

Refresh action data at a certain internal

Create a multistep action, as a first step use the following code:

const { interval } = await requireAsync('rxjs');
// internal is specified in miliseconds
return interval(5000);

Add the Load Table or any other load data step as the next one.

Safely parse JSON result into a variable

const items = {};
try {
  items = JSON.parse(data['items']);
} catch (e) {}

return items;

Last updated

© 2024 UI Bakery