2

I'm sure I'm doing something silly here.

I have got my component correctly retrieving data using wire and showing it on the screen via an Id getter.

I want to use that ID later on in the same javascript class to call an API with a dynamic parameter, how can I do this?

import { LightningElement, track, wire, api} from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
const FIELDS = [
    'Contact.ExternalId__c'
];
export default class HTTPCalloutInLWC extends LightningElement {
    @api recordId;
    @track claims;
    @wire(getRecord, { recordId: '$recordId', fields: FIELDS })
    contact;

    get Id() {
        return this.contact.data.fields.ExternalId__c.value;
    }

    // Making Callout using Fetch
    connectedCallback() {

        fetch("https://SOMEURL/IWantMyExternalIdHere", 
        {
<snip>
1
  • 1
    It strikes me that the issue is in using connectedCallback. The internal state of the component may not yet be fully initialized, especially where this comes from wires. I personally would move the call to fetch into a wire function, replacing your "contact" wire property, but only when the data is available.
    – Phil W
    Commented Jan 30, 2020 at 17:53

2 Answers 2

3

Don't write your FETCH code in ConnectedCallback().

Write a callback function like shown below :

@wire(getRecord, { recordId: '$recordId', fields: FIELDS })
wiredRecord({ error, data }) {
    if (data) {
       // put your fetch function here
    }
    if (error) {
        // show error message
    }
}
2
  • Thank you, this helped! Commented Feb 1, 2020 at 15:23
  • @JoeHowells Welcome!! Select as Best Answer if you think so
    – Mohit K
    Commented Feb 1, 2020 at 15:24
1

Simply add a callback function to handle the data returned by the wire function:

@wire(getRecord, { recordId: '$recordId', fields: FIELDS })
wiredRecord({ error, data }) {
    if (error) {
        let message = 'Unknown error';
        if (Array.isArray(error.body)) {
            message = error.body.map(e => e.message).join(', ');
        } else if (typeof error.body.message === 'string') {
            message = error.body.message;
        }
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Error loading wired data',
                message,
                variant: 'error',
            }),
        );
    } else if (data) {
        //put fetch function here
    }
}

Hope this helps.

1
  • Thank you, this helped! Commented Feb 1, 2020 at 15:22

You must log in to answer this question.

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