Showing results for 
Search instead for 
Did you mean: 

Code re-usability in PowerApps using User-Defined functions

In this article, I will be explaining how we can do the code reusability and why we need this in PowerApps so that we will have more control over code also achieve app's best performance.

Business scenario:
My business has an App to track all the leave request for every employee in the organization. I need to show the accumulated leave balances by each user on the app landing page (for the last 10 active users).


App performance Challenge:

On my App Start property, I am accumulating all the leave balances and showing on a grid, but if the logged-in user is HR/manager and he/she wants to reload the leave balances after an hour! if they click on the refresh button and I need to use the same code block for rebuilding the leave details as part of onSelect property of refresh control.

Note: I am forced to repeat the same code block if I go on this path. So I have implemented the below code reusability approach so all my code is centralized and easy to manage.


Implementing code reusability in PowerApps:
There are many approaches to achieve this, in my approach, I am using user-defined functions so that I can call my code block from any screen of my app.

Steps to be followed to achieve this:

  1. Add a screen in your app to add the reusable code blocks
  2. Add a toggle control on your that screen
  3. Name that toggle control as fncGetLeaveDetails 
  4. Set the default value of the toggle control to varGetLeaveDetails
  5. Now add your code to build a collection with accumulated leaves in OnChange event of the toggle control
  6. Add a button to refresh the collection with new details as and when HR / Manager wants to reload.
  7. OnSelect property of the app add this formula Set(varGetLeaveDetails,!varGetLeaveDetails)

That's all we need to do to achieve the performance with user-defined functions in Power Apps.


Happy Development in Power Apps !!