mardi 20 décembre 2022

Error: Missing target element || Stimulus 1.1.1 Rails 6

I have this error 'Error: Missing target element' in console when i try to select one target.

The main idea here is to iterate through an array of web_servers so I create one controller per instance and select one target per controller (the value is_available will change continuously, and I want to use action cable to monitor it).

My stimulus controller:

import { Controller } from "stimulus";
import consumer from "channels/consumer";

export default class extends Controller {
  static targets = ["status"];

  connect() {
    console.log('Will create subscription to: channel: "ScanServersStatusChannel" web_server_id: ' + this.data.get('id'));

    this.channel = consumer.subscriptions.create({ channel: 'ScanServersStatusChannel', web_server_id: this.data.get('id') }, {
      connected: this._cableConnected.bind(this),
      disconnected: this._cableDisconnected.bind(this),
      received: this._cableReceived.bind(this),
    });
  }

  _cableConnected() {
    // Called when the subscription is ready for use on the server
    console.log('_cableConnected');
    console.log(this.statusTarget);

  }

  _cableDisconnected() {
    // Called when the subscription has been terminated by the server
    console.log('_cableDisconnected');
  }

  _cableReceived(data) {
    // Called when incoming data from websocket
    const element = this.statusTarget
    element.innerHTML = data
  }
}

My view:

<% @web_servers.each do |web_server, index| %>
  <div data-controller="serverstatus" data-serverstatus-id="<%= web_server.id %>">
      <tbody class="accordion">
        <tr>
          <td id="web-server-id"><%= web_server.id %></td>
          <td><%= web_server.port_number %></td>
          <td><%= web_server.address %></td>
          <div data-target="serverstatus.status">
            <td><%= render 'admin/dashboards/web_servers/web_server_status', web_server: web_server%></td>
          </div>
        </tr>
      </tbody>
  </div>
<% end %>

Inside the partial:

<span ><%= web_server.is_available ? 'Disponible' : 'Non disponible' %></span>

Aucun commentaire:

Enregistrer un commentaire