[SalesForce] Calling Apex method (to insert a record) imperatively from LWC JS

I want to insert a record (Log) whenever I open a record from a custom object. I want to know if it is possible to call an Apex method in LWC JS without @wire? I have a function in my Apex class to insert a record in Salesforce. I know if I set (cacheable= true) on the Apex method, then I cannot do a DML operation.

My Apex method:

@AuraEnabled
public static void writelog(String message)
{
    System.debug('LogController.writelog called');
    System.debug('Writing Data');
     if(data.length() > 131072)
     {
          data = data.left(131069) + '...';
     }
     Custom_Object__c log = new Custom_Object__c (Log__c= message);
     insert log;
}

My JS:

This codes run whenever I open a record from a custom object.

import writelog from '@salesforce/apex/LogController.writelog';
export default class ProductVersion extends LightningElement {
get data()
{
    // some codes

    var msg;
    msg = "Logging starts";

    writelog({message: msg})
    .then({

    })
    .catch(error => {
        // eslint-disable-next-line no-console
        console.log(error);
    });

    // other codes
}

When I open the record, I see no error on my browser developer tools and on the Salesforce developer console. However, I don't see that the Apex method is being called either. How do I resolve this?

Best Answer

You are using a getter - it will be invoked only when the tracked property which is being used in template also changes. You can invoke it in connectedCallback to invoke on initialization of component.

connectedCallback(){
    var msg;
    msg = "Logging starts";

    writelog({ message: msg })
        .then({

        })
        .catch(error => {
            // eslint-disable-next-line no-console
            console.log(error);
        });
}