Code executing twice in window.retool.subscibe

Hello everyone. I am learning to use the custom component feature, however I am running into an issue that I do not understand.

My code so far is very simple, I only have a select element in my custom component. My HTML looks as follows:

<html>
  <body>
    
    <select id="sentenceSelect">
      <option value="">Select a sentence</option>
    </select>

  </body>
</html>

And my javascript is this:

<script>
  window.Retool.subscribe(function (model) {
    // subscribes to model updates
    // all model values can be accessed here
    const sentenceSelect = document.getElementById("sentenceSelect");
    const option = document.createElement("option");
    option.value = 1;
    option.textContent = model.name || 'default';
    
    sentenceSelect.appendChild(option);
    
  });
</script>

This is my model code:

{
  "name": "modelname",
}

As you can see I am using the window.retool.subscribe function to append options to the selector from my model data. However, something strange happens. Data seems to be appended twice to the selector, instead of once. The first time, the model data is NULL (and thus, the string "default" is displayed, and the second time, it appends the regular model data. This is what the component looks like:

Can anyone tell me what's happening here? And does anyone have a fix? Thanks alot in advance.

Hi @KoDev

It can happen that Retool send a null model, I guess because async cross communication is a difficult task.
In this case you just have to make sure to do noting, if the model is not set.
This is the workaround that I do all the time in my custom components.

Hope this help.

1 Like

This really helped me. Thanks a lot!