1
const fields = {};
        fields[NAME_FIELD.fieldApiName] = this.name;
        const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
        createRecord(recordInput)
            .then(beep => {
                this.accountId = beep.id;

            });
            console.log(this.accountId);

The console returns 'undefined'. How would I be able to get the Id? (@track accountId defined)

  • It returns an ID, can you add catch block as mentioned here to see ifthere are any errors? developer.salesforce.com/docs/component-library/documentation/… – Pranay Jaiswal Jul 18 '19 at 10:08
  • There are no errors, but this.accountId still remains undefined in the function. For Clarification: I am calling this function through a lightning-button. – Draccel Jul 18 '19 at 10:16
  • Shoudn't console.log(this.accountId); be inside the then block? – Pranay Jaiswal Jul 18 '19 at 10:17
  • Yeah you are right. But why is it necessary for it to be inside the block? – Draccel Jul 18 '19 at 10:25
  • Is there a way to get the Id of the record created immediately so it can be used elsewhere? – Draccel Jul 18 '19 at 10:34
2

createRecord is serverside call, and hence it's asynchronous in nature.

Now the thing about the async process is the returned value will only be present in the then block.

Let's look at the below piece of code.

createMyAccount(event){
            const fields = {};
            fields[NAME_FIELD.fieldApiName] = this.name;
            const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
            createRecord(recordInput)
                .then(beep => {
                    this.accountId = beep.id;

                });
            console.log(this.accountId);
        }

createMyAccount is an syncronous method, it sets the fields and triggeres the async process create record. The console.log(this.accountId); is part of sync process, and thus it returns undefined.

When you move it to then block, it will run when server finishes creating record, and as record creation was successful you will get Id.

createMyAccount(event){
            const fields = {};
            fields[NAME_FIELD.fieldApiName] = this.name;
            const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
            createRecord(recordInput)
                .then(beep => {
                    this.accountId = beep.id;
                    console.log(this.accountId);

                });

        }

So whatever operation you have to do with that Id, you have to do it in then block/

Src: https://blog.bitsrc.io/understanding-asynchronous-javascript-the-event-loop-74cd408419ff

| improve this answer | |
  • Ah I see, thank you for clarifying – Draccel Jul 18 '19 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.