FilamentF
Filament2y ago
6 replies
Will Aguilar

Call async JavaScript function from a Action

I have a TextInput that has a hintAction to copy a code to an NFC tag using Chrome's NDEFReader

TextInput::make('nfc_code')
  ->hintAction(
    Action::make('writeNfc')
        ->icon(getTeamIcon('microchip'))
        ->requiresConfirmation()
        ->action(function ($state, $livewire) {
            $livewire->js("await nfcHandler('$state')");
        })
  ),


JS function
window.nfcHandler = function(code) {
  if ('NDEFReader' in window) {
      const url = `${window.location.origin}/animals/${code}/tasks`;

      const ndef = new NDEFReader();
      ndef.write({
          records: [{ recordType: "url", data: url }]
      }).then(() => {
          new FilamentNotification()
              .title('Saved successfully')
              .success()
              .send()
      }).catch(error => {
          new FilamentNotification()
              .title(error.toString())
              .danger()
              .send()
      });
  } else {
      // for testing
      setTimeout(() => {
          new FilamentNotification()
              .title('NDEFReader not available')
              .danger()
              .send()

      }, 5000);
  }
}


The JS function works, calling the JS functions from Action works. However, the modal doesn't wait for the JS function, it closes as soon as I confirm on the modal. Is there a way to "wait" for the JS function to finish before closing the modal?

Any guidance will be greatly appreciate it
Was this page helpful?