Disambiguation: In previous lessons we’ve been talking about state-bound UI components. Unfortunate name clash, but here we’re talking about custom behavior that runs when the UI navigation enters a particular state (i.e. a new page). The two “state” concepts are completely unrelated…
UML state machines have a neat feature whereby you can specify a behavior (i.e. an event handler, or function) that executes at one of 3 stages in a state’s lifecycle:
entry behavior executes when the state machine enters a new state; the
do behavior executes during the state; and
exit executes when the state transitions away to some other state.
Name / Comment cell next to the behavior, and type a new function name:
Then double-click the name, and type in the code on the Code tab:
In the above example, you should see the message logged in the browser console each time the Register page is viewed.
Note the ES6-style arrow function. Currently there are no arguments passed into the function, but in a future update the domain objects in the current page will be passed in.
The ‘do’ function is called once when the page is first rendered, then repeated each time the page is re-rendered, e.g. due to a state change that causes a component in the page to redraw.
The ‘exit’ function is called once whenever the browser navigates away from the relevant page - i.e. when the state is exited.
Note that there’s essentially no guarantee that the exit code will run; e.g. the user might close the browser, and re-open it with the URL pointing to a different page in the web-app. In this case, the ‘exit’ code would have been avoided. So it should just be used for non-essential code such as debug logging.
Note: Be sure to click Save after editing any of the code functions in EA.
For React, the behaviour functions are generated as effect hooks, as follows:
Entry: The effect hook is run once when the page is first rendered (equivalent to “componentDidMount” in class-based React components)
Do: The effect hook is run on each rerendering of the page, e.g. due to a state change
Exit: The code is run in a
cleanupfunction returned from
useEffect(equivalent to “componentWillUnmount” in class-based React components)
The idea is the custom code will be able to run unchanged on different UI platforms. As we add new UI platforms, we’ll aim to preserve the above semantics so the code runs at roughly the same junctures on each.
For React, the behaviors for a particular state/page will be in the
.tsxfile of the same name - e.g. if the page is called Register, look in
Try to avoid writing platform-specific code in these functions. Of course, if it’s really needed, it’s needed - e.g. if the code triggers a page rerender, you may need to use a
dispatch call to keep the React UI responsive. However, keeping the code at a “business rules” level and well-scoped within its target domain should help avoid this issue.