Target element out of date

Hi,

This is my controller:

The problem is near the end of the connect method. So, if the URL contains a “manufacturer” parameter, I do a request which populates a with a bunch of 's. All I want to do after that is take the value of the parameter, find the associated option and set it to selected.

It fails because it cannot find an that matches. In Chrome’s dev tools, the Select is there with all the correct options. But JS, when I console log some stuff, just shows me that the select only has one default option and cannot find the matching element. It;s like the state of things is before the select was appended into.

How can I get my script to see the newly inserted options and preselect one?

Thanks,
Neil

import { Controller } from "@hotwired/stimulus";
import { get } from "@rails/request.js";

export default class extends Controller {
    static targets = ["selectBase", "select1", "select2"];
    static values = {
        url1: String,
        url2: String,
        param1: String,
        param2: String
    };

    connect() {
        if (this.select1Target.id === "") {
            this.select1Target.id = Math.random().toString(36)
        }

        if (this.select2Target.id === "") {
            this.select2Target.id = Math.random().toString(36)
        }

        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);

        if (urlParams.has('manufacturer')) {
            console.log('Has manufacturer');

            let params = new URLSearchParams();
            params.append("manufacturer", urlParams.get('manufacturer'));
            params.append("target", this.select1Target.id);

            console.log(params.get('manufacturer'));
            console.log(params.get('target'));

            get(`${this.url1Value}?${params}`, {
                responseKind: "turbo-stream"
            });

            this.select1Target.removeAttribute("disabled");

            if (urlParams.has('model_1')) {
                console.log('Has model_1');

                console.log(this.select1Target);

                console.log('#' + this.select1Target.id + ' option[value="Steeplechase"]');

                console.log(document.querySelector('#' + this.select1Target.id + ' option[value="Steeplechase"]'));
            }
        }
    }

What you want here is to await the promise that gets returned from the request.

await get(your_get_request_stuff...)
// code to happen after request...

that way it will ensure the request was performed and your new elements have been added before it moves on the next chunk of code which relies on them.

if you want to access stuff about the response you can save the result of the promise

const response = await get(your_get_request_stuff...)
if (response.ok) {
  // ensures that the request returned a successful status
}