0

Is there a good practice to conditionnaly get data from a component when this data can be passed by a parent?

Eg: I have a component that relies on data which he can get through a wire call or through a parent component, depending on its context (standalone or integrated in another component which will get the data for its child)

Current solution I use is to imperatively call my backend in the connectedCallback() :

import myFunc from '@salesforce/apex/...';

MyComponent () {
  @api recordId;
  @api data;
  @track _myFinalData;  // to be used by the component

  connectedCallback() {
    if (this.data == null && this.recordId != null) {
       myFunc()
        .then(result => {
            this._myFinalData = result;
        })
    } else {
      this._myFinalData = this.data;
    }
  }
}

1 Answer 1

0

You can separate these two functionalities into two different components instead of fetching data based on conditions from the connected callback:

  1. Fetching data from the wired method.
  2. Processing and displaying data by getting it from the parent component via a public attribute.

Basically create a separate wrapper component so you can write wire logic in that and treat that wrapper component as standalone. This method also simplifies the logic and keep it easy to change.

Alternatively, you can have a wired method called conditionally. I go went through many scenarios where I did not want the wire function to run unless some conditions are met.

To achieve this simply use a parameter that has a value of undefined. The wire methods don't get called if any of the parameter values is undefined. So you can set this value to undefined whenever you don't want it to be called. You can also use a dummy parameter for this purpose. This saves server calls.

Set this parameter value if you are passing data from the component.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .