The relentless Livewire Event Listener in JavaScript keeps on running without pausing

I need to create a solution where JavaScript listens for an event emitted by Livewire and performs a specific action. Currently, the JavaScript code is able to listen to the Livewire event, but it keeps executing continuously instead of just once per event. Below is an excerpt from my Laravel Livewire component:

    protected $listeners = [
        'reportFilterUpdated' => 'reportFilterUpdated',
        'eventListened' => 'eventListened',
    ];

    public function render()
    {
        $this->generateChartData();
        return view('dashboard');
    }

    public function generateChartData()
    {
        // Some other unrelated codes
        $this->emit('reportFilterUpdated');
    }

Here is the relevant JavaScript code I'm using:

document.addEventListener('DOMContentLoaded', () => {

    Livewire.on('reportFilterUpdated', _ => {
        console.log('event listened');
    });
    
});

Current output in the browser's console (it never stops printing):

dashboard.js: (97) event listened

Does anyone have any suggestions on how to ensure the action only executes once per emitted event? My goal is for 'event listened' to be printed only once in the console regardless of the number of emissions from my Livewire component. Any help would be greatly appreciated. Thanks.

Answer №1

Each time Livewire detects a change, the component undergoes rerendering. This includes changes triggered by form input or button clicks.

The render() function is invoked with every modification.

In your scenario, whenever a change occurs, $this->generateChartData(); is executed within your render() function. Thus, upon each alteration to the component, the render function will call and execute the generateChartData() function which contains an emit statement.

Consequently, each modification triggers a call to $this->generateChartData(); inside the render() method, emitting an event that JavaScript listens for each time it occurs.

It is generally recommended to keep the render function intact as-is.

If you wish for a specific process to run only once, utilize the mount() function, which executes solely upon the initial rendering of the component itself.

Below is an excerpt from the Livewire Docs illustrating the usage of the mount() function:

https://i.stack.imgur.com/ggeSO.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to manage json-parse errors in a node.js environment?

After countless hours of research, I am still unable to find a solution to my seemingly simple and common problem: In Node.js using Express, I want to retrieve JSON-data via http-POST. To simplify the process, I intend to utilize the app.use(express.json( ...

Unable to locate FFmpeg on the root server for Discord JS v13

After setting up my DiscordJS Bot on a new rootserver, I transferred all the files and launched the bot. Everything seemed to be working fine until I tried to run a command that involved the bot joining a voice channel and playing audio. At this point, an ...

Verification is required for additional elements within the div block once a single checkbox has been selected

Currently, I am working in PHP using the CodeIgniter framework. I have a question regarding implementing a functionality with checkboxes and validation using jQuery. Here is the scenario I want to achieve: There are four checkboxes, and when one checkbox ...

When utilizing exit-hook with process.on('SIGTERM'), child_process spawn requires two control-c commands to exit properly

I have the following program running: const { spawn } = require("child_process"); const exitHook = require("exit-hook"); exitHook(() => { console.log("Leaving"); }); spawn("my-program", ["my-args"], { stdio: "inherit" }); // Long running server ...

javascript/jquery form validation problems/support needed (jQuery)

Long story short, I am facing an issue with my code and seeking some guidance. I have various functions to perform different checks. For this particular example, I have a form with a default value of "enter name here" for one field. Here is the HTML snipp ...

Using Ajax to invoke a C# webmethod

I'm trying to call a webmethod defined in this specific class <%@ WebService Language="C#" Class="emt7anReyady.myService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Linq; usi ...

Creating a stunning art exhibition using React Native

Currently, I am in the process of creating a gallery component that utilizes both the scrollview and image APIs. I'm curious about how the scrollview manages its child components when it scrolls down. Does it unmount the parts that are not currently ...

Reset input field when checkbox is deselected in React

How can I bind value={this.state.grade} to clear the input text when the checkbox is unchecked? The issue is that I am unable to modify the input field. If I were to use defaultValue, how would I go about clearing the input box? http://jsbin.com/lukewahud ...

Having trouble with redundant code while updating state in ReactJS - React JS

Currently, I am working on a prayer times web app using reactJS (nextjs). To achieve this, I first fetch the geolocation coordinates and then retrieve the city and country name based on these coordinates. Following that, I obtain the prayer times for the s ...

What are some strategies for blocking URL access to a controller's method in Rails 3?

My goal is to enhance my Rails 3 application by integrating Javascript/jQuery code that retrieves data from the server and updates the page based on the fetched information. I am considering implementing jQuery's $.get() method for this purpose: $.g ...

Implement rotation in Three.js that mirrors the functionality of Blender

Is there a way to permanently change the default rotation of a mesh in three.js after it has been loaded? For example, if I load a mesh with a rotation of 0,0,0, can I then rotate it 90 degrees on the X axis and set this new rotation as 0,0,0? It's i ...

Is there a way to set a default CSS background image using JavaScript in case the specified

When working with regular CSS, I can easily set a fallback image using this code in case the primary image is not available: .container { background-image: url(pics/img.webp), url(pics/img.png); } But when it comes to setting styles in JavaScript (such ...

What could be causing my scene to fail to render?

I'm attempting to adapt this particular example into CoffeeScript. Below is a snippet of my code: class Example width: 640 height: 480 constructor: -> @camera = new THREE.PerspectiveCamera 45, @width/@height, 10000 @cam ...

Build a brand new root component in Vue JS

I am facing a challenge with destroying and re-creating the root application component. Below is my template structure: <div id="app"> {{ num }} </div> Here is the code I have implemented: if (app) { app.$destroy(); } else { ...

A guide on triggering a function when a button is clicked in reactjs

Can anyone please help me with this issue I'm having: how do I execute a function when a button is clicked? I currently have the following code but it's not working export var Modulo = React.createClass({ prom1: function () { retur ...

How can one ensure the preservation of array values in React?

I'm struggling to mount a dynamic 'select' component in React due to an issue I encountered. Currently, I am using a 'for' loop to make API calls, but each iteration causes me to lose the previous values stored in the state. Is t ...

What is the best way to avoid the pipe symbol in jade formatting?

When working with jade, the pipe symbol (|) is utilized for displaying plain text. But what if you need to actually write it on the page? Is there a way to escape it in Jade? ...

Can you help me streamline the code for the Sign Up Form app using React and jQuery?

Hi everyone, this marks my debut post on StackOverflow as I embark on the journey to become a full stack developer. To enhance my skills, I've been using FrontEnd Mentor for practice and managed to solve a challenge with the code provided below. Any s ...

Unlock the power of Odoo by learning how to seamlessly add custom field attributes without the need for modification

Currently, I am facing an issue with using my custom attribute for fields known as sf_group. The problem is that this attribute is not included in the field description retrieved via fields_get(). Is there a way to incorporate this custom attribute into th ...

Leveraging AJAX, PHP, and MySQL for showcasing tabular information

My goal is to dynamically display a column of data labeled as [pin], depending on the values of [plan] and [order_id]. Specifically, when plan=9 and order_id=0. I am looking to achieve this without having to reload the entire page by utilizing Ajax. Below ...