Variables with Custom Code

There might be an use case where you want to use an App Variable or a Device Variable with Custom Code.

All App and Device variables are shared via a GlobalVariablesContext. If you have defined a variable of either type, you can access them in your Custom Code through the shared context.

Access in JSX Components

By accessing an App or a Device Variable in a JSX Component, you can do the following:

  • read the value of the variable
  • modify/update the value of the variable

To access a Global Variable in JSX, the initial step is to import the GlobalVariableContext to access the module. You cannot use the GlobalVariableContext API without importing

If your file is located at the Top Level location (/), import using

import * as GlobalVariableContext from './config/GlobalVariableContext';

Otherwise if it's in the Custom Files location (/custom-files) directory, use

import * as GlobalVariableContext from '../config/GlobalVariableContext';

Reading a value with useValues

useValues is a function that returns an object containing current values of App Variables and Device Variables in your App.

Here is an example snippet on how you can read the value of an App or a Device Variable:

import React from "react";
import { Text } from "react-native";

import * as GlobalVariableContext from "../config/GlobalVariableContext";

export const MyVariableDisplay = () => {
  const variables = GlobalVariableContext.useValues();
  
  return <Text> { variables.myGlobal } </Text>
};

Updating a value of with useSetValue

useSetValue is a function that returns a setter function that, when called with an object containing key and value fields, will set an App Variable or a Device Variable with the specified key to the specified value.

import React from 'react';
import { Button } from 'react-native';

import * as GlobalVariableContext from '../config/GlobalVariableContext';

export const MyComponent = () => {
  const setGlobalVariable = GlobalVariableContext.useSetValue();

// RANDOM_VARIABLE is defined as an App Variable

  return (
    <Button
      onPress={() => setGlobalVariable({ key: 'RANDOM_VARIABLE', value: 'new value' })}
      title="Update a Variable"
    />
  );
};

Access in Functions

To read the value of an App or a Device Variable in Functions, you can do the following:

  • Inside your Function use the syntax Constants.variable where variable is the name of your App or Device variable.
function myFunctionName() {
  return Constants.appVar;
}

Use Constants in a custom function like above will automatically add it inside the screen component. Here is an example:

600

To update or modify a value of an App or a Device variable use Set Variable action type from the Interactions tab (last tab) in the Properties Panel.