'Alpine js setting data from external js

I'm trying to show a modal by changing the data from an external javascript file after a successful call to the Api, here's what I've tried:

<div class="modal-wrapper" x-data="modalData()">
    <div class="modal" x-show="open">
      <div class="modal-content rounded overflow-hidden shadow bg-white" id="modal-content">

      </div>
    </div>
  </div>
function modalData() {
  return {
    open: false,
    closeModal () {
      this.open = false;
    },
    openModal () {
      console.log('This gets logged just fine');
      this.open = true;
    }
  }
}

And in the successfull ajax call I'm trying to do:

modalData().openModal();


Solution 1:[1]

It's a little bit hacky solution, but you can use the _x_dataStack attribute to access the element data from the external script:

let modal = document.querySelector('.modal-wrapper')
modal._x_dataStack[0].openModal()

It uses an internal API (tested on 3.8), so it may wont work in the future. A less hacky way would be using a store and mutate the state via e.g. window.Alpine.store('open', true).

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Dauros