'Rails - StimulusJS: how to set target value from within setTimeout?

In my Rails-Stimulus controller, I fetch data in a loop from a function in which I've setTimeout. How do I set the target value from within the setTimeout?

My form partial

<%= text_field_tag :first_date, "Select Date One", data: {controller: 'flatpickr'} %>
<div data-controller="hist">
    <div data-hist-target="one"></div>
    <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 border border-blue-700 rounded"
        data-action='hist#get_history'>
        Hist
    </button>
</div>

My controller

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "one" ]
  
  connect() {
    
  }

  get_date_history(aDate) {
    setTimeout(function() {
      var history = new Array()
      let month   = aDate.slice(5,7)
      let date    = aDate.slice(8,10)
      let url     = 'http://numbersapi.com/' + month + '/' + date + '/date'

      for (let step = 0; step < 5; step++) {
        fetch(url)
          .then(response => response.text())
          .then(function(data)  {
            history.push(data)
          })
          .catch(err => console.log('Request Failed', err)) // Catch errors
      }
      // can we set oneTarget value here? how?
    }, 2500)
  }

  get_history() {
    var date = document.getElementById("first_date").value
    this.get_date_history(date)
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source