[SalesForce] Refresh lightning component from Visualforce Page on button click

I have a lightning component that is placed on Visualforce Page via lightning out. I have a button on Visualforce Page on click on which the lightning component should refresh.

Is there a way I can achieve this?

Best Answer

I have recently encountered the same situation. If anyone is looking out for the solution, here is what you need to do !

let me first reframe the situation here,

"Lightning Component is invoked from Visualforce Page using ltng:outApp. You would want to change data or have control on already created Lightning Component from a button click on Visualforce Page"

Solution:

You might have used $Lightning.use already in Visualforce page inside which you create Lightning Component using $Lightning.createComponent.

Now, create a lightning event , let's say "refreshEvent" and handle the event in your lightning component, "MyLC" using aura:handler

<aura:handler event="c:refreshEvent" action="{!c.init}"/>

You need to fire this event inside Visualforce page on button click. But when you implement this, you will be getting error "Cannot read property of fire of undefined".

Let's go back to basics, when you are using Lightning:use, you are implementing Lightning framework inside visualforce page, you can fire lightning event only inside this framework. So, when you fire event directly inside the page, console will not understand fire command. You need to find a way to fire the event inside Lightning:use.

My requirement was to refresh or initialize Lightning Component when I click on a button in Visualforce Page. For this I used a boolean variable in javascript, using which I either create Lightning component or fire Lightning Event. Please check the sample code below,

In the page:

<li><a  href="#" onclick="callLC();">test</a> </li>

Javascript:

<script> 
   var invokeLC = true;
   
   function callLC(){
    $Lightning.use("c:yourLightningApp",    
            function() {
                console.log('invokeLC'+invokeLC);
                if (invokeLC) {                  
                    $Lightning.createComponent(
                        "c:MyLC", 
                        function(cmp) {
                        }
                    );
                }else {
                    fireEvent();
                }
                
                invokeLC = false;
            },          
        );    
   }
   
    function fireEvent() {           
        var myEvent = $A.get("e.c:refreshEvent");
        myEvent.fire();
    }

</script>