FHIR Chat · client-js best practices · smart

Stream: smart

Topic: client-js best practices


view this post on Zulip Ford Parsons (Jul 08 2021 at 00:06):

Hi all, I'm using the smart-on-fhir/client-js library and I have a style question.

On page load, I list some Observations. I also have a button to create a new Observation.

Style-wise, should I call FHIR.oauth2.ready once (on page load) then store the client for later use (on button click)? Or is it better to call FHIR.oauth2.ready twice -- once on page load, then again inside the button click event handler?

It works either way, but I'm hoping to get feedback on the most idiomatic approach.

@Josh Mandel or @Vladimir Ignatov I feel like you'd have have some opinions about this.

Thanks,
Ford

view this post on Zulip Vladimir Ignatov (Jul 08 2021 at 15:46):

ready is designed to be called once. You should store the client and reuse it later if possible. Even though it works, you should avoid calling ready multiple times, especially in event handlers where user can "feel" a performance impact. It is a complicated function, but you can think of it as a singleton client factory. When you call it multiple times it will do certain amount of work (which is unnecessary to do more than once) and it will eventually return a client instance that is the same as the one you've gotten on previous calls.
Internally, ready will detect if this is an initial page load (a redirect from the authentication server). If it is, it will do a bunch of things to complete the auth flow (like exchanging the code parameter for an access token) and will return a client once everything is done. Otherwise it assumes this to be a page refresh and will create and return a client based on the previously stored state. That said, if you call it multiple times it would still work but there is no reason to do that if you can avoid it.

There are two cases to consider in browsers:

  • If you have a simple setup where everything happens on a page that is loaded in the browser (for example some page of a website), then call ready on page load and keep a reference to the returned client for later use if needed.
  • If you have a "single page app" having it's own routing, then make sure you call ready before the app is initialized and store the client in a way that makes it accessible from all the routes that might need it. For example in React apps, a SMART client can be stored in context and later used by components that need it.

view this post on Zulip Ford Parsons (Jul 08 2021 at 18:34):

Thank you, Vladimir, for such a thoughtful response. Calling ready once makes total sense. We're not using a SPA yet, but I appreciate the guidance there as well. Thank you for creating/maintaining such a great library.


Last updated: Apr 12 2022 at 19:14 UTC