7

Could be a very basic question. I am wondering how I can call a function from another in LWC.

for eg:

export default class testUtil extends LightningElement {
hangleChange(evt){
  this.inputcheck = evt.detail.value;
  if(inputval == true){
     showtoast(inputval);
  }
}
 showToast(inpval) {
        const event = new ShowToastEvent({
            title: 'Get Help',
            message: 'Input val changed.'+ inpval,
        });
        this.dispatchEvent(event);
    }
}

I assumed I could use testUtil.showToast(inpval) even that does not work I get undefined function, in case of aura framework I can call functions in the helper method as much as I can, am I missing something or is there no way to build reusable functions in LWC?

4

Here is how I would do if I feel this function is used only in the current component. The trick here is to use the prefix this. when invoking functions in the same class.

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';


    export default class TestLwc extends LightningElement {
        hangleChange(evt){
            this.showToast('foo');
        }

        showToast(inpval) {
            const event = new ShowToastEvent({
                title: 'Get Help',
                message: 'Input val changed.'+ inpval,
            });
            this.dispatchEvent(event);
        }

    }
2
  • this sounds a little more easier and promising, i will give this a shot – Rao May 30 '19 at 18:17
  • this works better than the first approach and due to the simplistic approach I am changing my vote here :) – Rao May 30 '19 at 18:46
15

A "helper" class would be a utility component.

For example, you can write the following code:

import { ShowToastEvent } from 'lightning/platformShowToastEvent';
// This is the testUtil component
function showToast(cmp, inpval) {
    const event = new ShowToastEvent({
        title: 'Get Help',
        message: 'Input val changed.'+ inpval,
    });
    cmp.dispatchEvent(event);
}

export { showToast }

(Note: this is a complete JS file)

Which you would then use in your other components:

import { LightningComponent } from 'lwc';
import { showToast } from 'c/testUtil';

export default class MyDemo extends LightningComponent {
    connectedCallback() {
        showToast(this, 'This is a demo toast');
    }
}

There is no literal equivalent to helper files in LWC. This design simplifies development and provides an easy way to share functions between components.

7
  • Are there any specific design patterns to follow with lwc is there a good place to get started. I have seen a few code samples being JavaScript everyone has their say on how things work. Hence the question. I can open this up as a separate question if you think that would be beneficial – Rao May 30 '19 at 0:47
  • @Rao I haven't used enough LWC to give this any serious thought, and it might be off-topic because of the inherent "opinion-based" nature of such a question, but I think it could be an interesting question if you frame it correctly. – sfdcfox May 30 '19 at 1:10
  • @sfdcfoxI am trying to follow this exact set up so that I can create a utility file where these re-usable functions will live. My issue is this helper js file you showed with the showToast function is throwing an error because dispatchEvent comes from lwc I believe? TypeError: this.dispatchEvent is not a function. How can I dispatch this toast event without that being there? – SBB Dec 13 '19 at 18:12
  • @sfdcfox did you create the file inside the same component bundle? The reason why I am asking is that I do not want to create helper classes in each component bundle doing the same thing. – Kiran Machhewar Mar 23 '20 at 2:36
  • @SBB I missed your comment (you missed a space). I'll have to amend this answer when I get a moment, it was more of a "proof of concept" than something I know works. Thanks for the comment on this. – sfdcfox Mar 23 '20 at 3:07
3

Isolating logic outside of the main ES6 module for your component is a good idea, since it can make a complex component's high-level design easier to scan. If you are using Jest and can justify focusing your testing efforts on the helper logic, this approach can also assist in making those tests run much faster, since Jest won't have to load all the child component dependencies referenced in your HTML template.

If you want to reuse the code in multiple components, use @sfdcfox's solution. If not, you can add a helper file to your component bundle and import it.

A helper like this (and yes, this is a complete file)...

// appHelper.js
export const helper = {
    addSix(number) {
        return number + 6;
    },
    changeMyNameToBob() {
        this.name = 'Bob';
    }
}

... can be used in the main module like this...

// app.js
import { LightningElement, track, api } from 'lwc';
import { helper } from './appHelper.js';

export default class App extends LightningElement {
    @track name = 'Jim';
    @track number;

    connectedCallback() {
        this.number = helper.addSix(4);
        helper.changeMyNameToBob.call(this);
    }
}

Note the use of function.prototype.call() to pass the module's this context into the helper function.

The helper file lives in the same directory as the component's other files, like this:

force-app
└───main
    └───default
        └───lwc
            └───app
                |   app.html
                |   app.js
                |   appHelper.js

See playground link

1

There's no concept of a helper per se, but you can easily share code by using standard javascript modules (aka ES6 modules).

You can also read more about sharing code here: https://lwc.dev/guide/reference#modules

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.