Data API timing issue?

Hi Guys,

I’m just wondering if there is an issue with timing on the Data API or am I missing something.
I’m testing making a quiz and when I try to get the answer data attribute that I set on the question controllers DOM element it always comes back false. I can see it in the DOM though so I know it’s being set.

question_controller.js

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

  answer(e) {
    var event = new Event("answered");

    this.element.dispatchEvent(event);

    this.currentAnswer = e.target.value;
  }

  set currentAnswer(value) {
    this.data.set("answer", value);
  }
}

quiz_controller.js

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

  checkQuestion(e) {
    let q = this.application.getControllerForElementAndIdentifier(
     e.currentTarget,
     "question"
    );
    console.log(q); // Controller
    console.log(q.data.has("questionAnswer")); // false
  }
}

I’d expect q.data.has("questionAnswer") to be true. I tried q.data.has("answer") too and that’s also false. Is there a timing issue here e.g stimulus can’t pick up the change in time or have I missed something?

Appreciate any help, thanks.

Ah just figured it out :slight_smile:

I was setting the value in question controller after dispatching the event.

It should be…

this.currentAnswer = e.target.value;

this.element.dispatchEvent(event);

And then in the quiz controller the correct call is…

console.log(q.data.has("answer"));

Now it’s working perfectly :+1: