isDerived util

Description

We have discovered a new pattern in Frontity: Sometimes, some props of the state are defined as “derived”, but can be overwritten by the user.

And sometimes, other parts of the application may want to know if that was the case or not.

@mmczaplinski discovered how to do it in this thread Make the backend URL a global setting, but the code is complex, so we could introduce an isDerived tool to check for this.

Examples

The best example is state.wpSource.isWpCom:

  • By default, it is derived from the value of state.source.api.
    • If state.source.api is a WP.com subdomain, it returns true.
    • If state.source.api is not a WP.com subdomain, it returns false.
  • It can be overwritten by the user to "true" when state.source.api is not a WP.com subdomain but the site is still a WP.com (for personal and premium plans).

Possible solution

As suggested by Michal, something like this could work:

const isDerived = (obj, propName) =>
  typeof Object.getOwnPropertyDescriptor(obj, propName).value === "function";

This means that the API to check if state.wpSource.isWpCom is derived is:

isDerived(state.wpSource, "isWpCom");

I don’t think there is a way to make it work with isDerived(state.wpSource.isWpCom) in JavaScript, so this is as good as it gets.