# Using conditional logic with Calculated and API variables

There are plenty of reasons to conditionally render questions in your flow - that is, either present or hide questions because of specific conditions. Some factors may be based on the information your users provide in their answers, like rendering certain questions based on age, or it could be based on factors external to that, like a marketing team hiding an offer that is out of season.

Fortunately, the synergy between Formsort’s conditional logic and API and Calculated variables allows us to automate when questions should be available to the users filling out our forms. But, like anything, this takes a little bit of configuring.

## Using calculated variables to hide questions

The power of calculated variables lies in the flexibility they provide by using Javascript functions (in Typescript format). This requires a little bit of JS/TypeScript familiarity, but it’s a powerful tool!

Below, we’ll go over a couple examples of using Calculated Variables for creating logic.

### Ex 1:

In this example function, we’ll return a Boolean true/false value based on whether or not the user in inside or outside the hours of operation, which are 9am - 5pm, M-F. This will require no direct input from the user, but instead will draw the local time from their browser.

In the variant we’re going to create this logic in, let’s head to our **Calculated Inline** tab under **Variables**, and then into the Calculated variable editor.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FhuDnsERv1is1otwkoeKU%2Fex1-1.png?alt=media&#x26;token=aabfbd3f-b4b9-4d72-ba04-2400dba6fed9" alt=""><figcaption><p>Add the calculated variable</p></figcaption></figure>

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2Fwb6CtZDYMW2GrttIhcGd%2Fex1-2.png?alt=media&#x26;token=a44a19ad-0157-47f2-ab21-f765cb15d696" alt=""><figcaption><p>The Calculated variable editor</p></figcaption></figure>

Let’s give the variable a name - we’ll call this one `dayparting_offers`, change the Variable Type to `Boolean` so Formsort knows to expect a T/F return, and drop the code into the **Getter Function Body**.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FZOVQDlVLGEUX4bLnAkn3%2Fex1-3.png?alt=media&#x26;token=c9cb9a93-4af2-4d9d-ba59-63f80c86ebb6" alt=""><figcaption><p>Setting up the variable</p></figcaption></figure>

{% hint style="info" %}
You can check the function using the “Test API variable” section at the bottom of the editor.
{% endhint %}

Here is a copy of the code we’re using:

<pre class="language-javascript" data-overflow="wrap"><code class="lang-javascript">function myFunction(): boolean { // readonly line
<strong>  var now = new Date();
</strong>  var hours_in_GMT = now.getUTCHours();
  var days_in_GMT = now.getDay();
  var days_in_desired_timezone = days_in_GMT;

  //time difference to GMT
  //In this case EST is 5 hours behind GMT
  var time_difference_to_desired_timezone = -5;

  var hours_in_desired_timezone = hours_in_GMT + time_difference_to_desired_timezone;

  //if its past midnight in GMT, make sure to adjust
  if (hours_in_desired_timezone &#x3C; 0 ) { days_in_desired_timezone = (((days_in_desired_timezone - 1) +7) % 7);
 hours_in_desired_timezone = hours_in_desired_timezone + 24;
<strong>  }
</strong><strong>  
</strong>//set the parameters for open hours using military time where Sunday is 0
<strong>  var start_time;
</strong>  var close_time;

  if ([1,2,3,4,5].indexOf(days_in_desired_timezone) > -1) {
  start_time = 9;
  close_time = 17;
  }

  else {
  start_time = 0;
  close_time = 0;
  }

  if (hours_in_desired_timezone &#x3C; close_time &#x26;&#x26; hours_in_desired_timezone >=   start_time) {
  return true;
  }

<strong>  else {
</strong>    return false;
  }
}    
</code></pre>

Now, lets use this variable to create logic on steps we only want available inside the hours of operation.

* In **Content**, head to the step we’re putting the logic on. Here, it is going to be Step 1.
* Click **Logic** → **Show conditionally** → **Add condition…**

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2Fngv0IIQ3KDQ679AKhsS9%2Fex1-4.png?alt=media&#x26;token=9efeaf0f-1453-45d0-87fe-ff63ba16827b" alt=""><figcaption><p>Navigate to Step logic menu</p></figcaption></figure>

* Select our variable `dayparting_offers` in the variable logic editor, and set it equal to **true**. **Save condition**.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FEA1EWpQcmLZdviojcGgY%2Fex1-5.png?alt=media&#x26;token=cb17f760-6113-4cf7-9ad0-55a61d7fe592" alt=""><figcaption><p>Adding the step logic</p></figcaption></figure>

* You can repeat this on Step 2 as well, but instead set the variable value to **false**.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FmANii3lKix3wOnbEkv5A%2Fex1-6.png?alt=media&#x26;token=dd87f914-154f-46fe-a5dd-495e039ac19d" alt=""><figcaption></figcaption></figure>

* You should see that the step logic will be visible on the steps we’ve set it on.

Now, depending on your local time, you will see either Step 1 or Step 2. Try it out in Live Preview!

### Ex 2:

This next example will hide a step based on our user’s age. This will require us to take the user’s `date of birth` response as an input to our calculated variable, run a function that will return an `age`, and set our step logic based on that age.

{% hint style="info" %}
Setting logic against a [date object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) can be tricky and unreliable. If you opt to filter users based on their age, it’s recommended to use this method, which sets logic against a [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number).
{% endhint %}

First, let’s create a question to capture the user’s dob.

* At the desired step, choose “Add question” and select the [Date](https://docs.formsort.com/building-flows/content-types/date) component. Set the **Variable** name (we’re using `dob`).

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FZLhqGqC3vVbfrd4RPWQ7%2Fex2-1.png?alt=media&#x26;token=61461534-073e-43ed-84be-8f3859336c1d" alt=""><figcaption><p>Naming our variable</p></figcaption></figure>

Now, we can take this input and dynamically create an age, depending on the user’s answer.

Head to **Calculated Inline** in our **Variables** section, and “Add calculated variable”.

* Give the function a name (we’ll call this one `age`) and set the **Variable Type** to **number** so Formsort knows to expect an integer.
* Toggle “**Uses other variables**”, and select `dob` from your variable list.
* Drop in the function

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FwFEAm9LMDw9FTj7ml14T%2Fex2-2.png?alt=media&#x26;token=ff172309-769f-416e-9a4d-89f70e29fe4c" alt=""><figcaption><p>Set the dependent variable</p></figcaption></figure>

{% hint style="info" %}
You can check the function using the “Test API variable” section at the bottom of the editor.
{% endhint %}

Here is a copy of the code we’re using:

{% code overflow="wrap" %}

```javascript
// dob is taken from our "Uses other variables" input
function myFunction(patient_dob: string): number { // readonly line
  const ageDifMs = Date.now() - (new Date(dob)).getTime();
  const ageDate = new Date(ageDifMs);
  return Math.abs(ageDate.getUTCFullYear() - 1970);
}
```

{% endcode %}

Now, lets use this variable to create logic on steps for users *at or above a certain age*.

* In **Content**, head to the step we’re putting the logic on. Here, it is going to be Step 3.
* Click **Logic** → **Show conditionally** → **Add condition…**

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FmLoEhGMS1EaxdXIFNxrI%2Fex2-3.png?alt=media&#x26;token=82d44dde-f0e0-4673-aaed-97a2c503aee7" alt=""><figcaption><p>Adding Step logic</p></figcaption></figure>

* Select our variable `age` in the variable logic editor, and set it to **greater than 17**. **Save condition**.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FKcRDspjDWPTmVuKpe74T%2Fex2-4.png?alt=media&#x26;token=a6b67a8d-9116-4c22-aab7-7a10e6282e20" alt=""><figcaption><p>Creating the Step logic</p></figcaption></figure>

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2F17UYpeJ8J3YjuIpxcFkV%2Fex2-5.png?alt=media&#x26;token=bbfcf2a1-d47e-467f-b8ea-07aa11176c65" alt=""><figcaption><p>The inline Step logic indicator</p></figcaption></figure>

Now, if our user’s `dob` puts them at an age that is younger than 16, they will skip Step 3 and move right on to Step 4. Try it out in Live Preview!

For more information on Calculated Variables and the options in our Calculated Variable editor, see our [docs](https://docs.formsort.com/building-flows/schemas/calculated-answers)!

## Using API variables to hide questions

[API variables](https://docs.formsort.com/building-flows/schemas/api-answers) make it possible to fetch data from a server that returns JSON responses. This server can be one you own, or it can be a 3rd party server that has information you need. As long as it returns a JSON response, and *you* can provide authentication into it (if necessary), we can ping it.

Once the API call returns the information we need, we can use the response to create logic on the steps we want to conditionally render.

### Example

In the example below, we will [**template**](https://docs.formsort.com/building-flows/adding-content/using-answers-in-templates?q=templat) a user’s response into our call to the [World Time API](http://worldtimeapi.org/) to determine their timezone, and thus determine which questions to hide.

First, let’s set up a question to find out where the user lives.

* Head into your variant and create the question. We’re using a [select question](https://docs.formsort.com/building-flows/content-types/select) here to provide a list of possible responses for our user.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FUtKhe3wzQrKZWqqxwPdB%2Fex3-1.png?alt=media&#x26;token=115c27f9-60e2-460f-8d17-3e9e53dd24b0" alt=""><figcaption><p>Creating our Select question</p></figcaption></figure>

* Give the variable name something recognizable. This question will have the variable name `user_city`.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2F8zKy37WaWST6oEzeVXPt%2Fex3-2.png?alt=media&#x26;token=2e1c232c-d645-4f4f-b8d8-4b50b79d366c" alt=""><figcaption><p>Naming the variable</p></figcaption></figure>

Now, let’s set up the API variable to return the time zone, based on the user’s answer.

* Head into **Variables** → **API lookups** and then “**+Add api variable**”.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FD1vP5lzPjkzu7DiccHXY%2Fex3-3.png?alt=media&#x26;token=3ea1cd04-0c2a-4bfe-be6b-741a4dc882fa" alt=""><figcaption><p>Adding the API variable</p></figcaption></figure>

* Add a variable name, and set the [**variable type**](https://docs.formsort.com/building-flows/schemas/api-answers#variable-type). Variable type is the expected data type we’ll be receiving from the API response (i.e. string, number, boolean, object, array).
* If we call this particular API with the `area` and `region` specified in the URL path, we will get an object return with the timezone information about the region.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FiQ1NFkxhHQgVN2NMpQxe%2Fex3-4.png?alt=media&#x26;token=9c9740b7-8585-4164-9856-34c526c9098c" alt=""><figcaption><p>Example call with area: America and region: Denver</p></figcaption></figure>

* Now that we know what kind of return to expect, we can add the variable value of `user_city` to our URL path, to make the API call dynamic.
  * Click “**Variables…**”, select `user_city`, and paste the variable into the URL path.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2F8P6vNInWyO3oCKMFiXnW%2Fex3-5.png?alt=media&#x26;token=c0463ba0-c170-4249-a470-09666b25bf6e" alt=""><figcaption><p>Open the available variables menu</p></figcaption></figure>

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FnnX6FJmjhQt48m7CHxCo%2Fex3-6.png?alt=media&#x26;token=7a8a2c6f-53d7-4519-bd9a-7a231359b887" alt=""><figcaption><p>Grab the variable we want</p></figcaption></figure>

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FaPggBIZxGqhiNDgusQdg%2Fex3-7.png?alt=media&#x26;token=b65cd762-bafa-483a-8767-d114e4239c64" alt=""><figcaption><p>Paste the variable into URL path</p></figcaption></figure>

* Now, we can double check the API call using the **Test API variable** section to make sure we’ll get the response we want. Select a value from the **USER\_CITY** dropdown, then hit “Send test request”.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FQoyQsN5KcmJFcxSOZYov%2Fex3-8.png?alt=media&#x26;token=41adf69d-7126-4674-b36e-046e05370650" alt=""><figcaption></figcaption></figure>

* Looks like we have a matching result! All we want from this call is the value for the `abbreviation` field in our return. Let’s use the **JSON Accessor** in **Result processing**.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2F68EfPUx31sxwkYNpBGO0%2Fex3-9.png?alt=media&#x26;token=1da4d74d-ab5e-4001-9484-233f4d461613" alt=""><figcaption><p>Error? </p></figcaption></figure>

* We returned an error! The API editor is still expecting an object, but the JSON accessor is returning string value. Let’s adjust our expected **variable type** and re-test.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FaYmCkKArUUrYH1Ihrr5m%2Fex3-10.png?alt=media&#x26;token=43f8eb50-c9d3-4ea2-b3ed-a804f4f76d29" alt=""><figcaption><p>Success! Denver is in MST</p></figcaption></figure>

We have the question we need to grab our user’s city, and we have confirmed that our API call will work with that information. All that’s left to do is create logic on the questions we want to hide, depending on the user’s time zone.

* Let’s create a Step that will not be available to users in “MST”. On that step, head to **Logic**, toggle **Show conditionally** on, and create the logic required. **Save condition**.

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2Fsej7qaSkC4JAIFWk3cVg%2Fex3-11.png?alt=media&#x26;token=6fed0479-5a0a-443e-b6dd-98071b28b3f7" alt=""><figcaption></figcaption></figure>

* Now, when a user answers “Denver” to question 1, they will not see question 2, and will instead skip to question 3. Try it out in Live Preview!

This is one simple API variable use case, but there are a lot of different ways the API variable editor can be configured, like using a mapping function to parse API responses, adding a URL fallback in case the API is unavailable, or making the API fetch conditional on some other conditions.

Make sure to see our [API Variable documentation](https://docs.formsort.com/response-data-collection-and-management/variable-schema/api-answers), or, if you’re like us, play around with it and see what you can do!
