0

Inside my html file, I have a script tag, of type module, where I import functions from Firebase via CDN.

One such function is an await function called setDoc. I need to use setDoc within a function I have written called save() which is triggered by a button.

What I have tried: The first error that I got is that save() "is not defined at HTMLButtonElement.onclick"

I moved my save() function in a separate script tag (which is not a module type) and it now works and is triggered upon a button click. However, I can't use the await Firebase function even though my save() is prefixed with async, because I need to import the Firebase functions again within the separate script tag. But I can't import the Firebase functions without making the separate script tag's type "module". So it feels kind of a circular problem for me.

How can I go about implementing the await method setDoc properly?

1 Answer 1

2

You can simply export the save method and import it and save it on window. As anything defined in a module is private to that module, explicity setting it on window is required.

https://codesandbox.io/s/stackoverflow-69083332-using-an-exported-function-as-an-event-handler-s9x9x

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Exported Function as an event</title>
    <script type="module">
      import { save } from "./module.js";
      window.save = save;
    </script>
  </head>
  <body>
    <button onclick="save()">
      Save
    </button>
  </body>
</html>

module.js

export async function save() {
  return new Promise((resolve) => {
    setTimeout(() => {
      alert("Saved");
      resolve();
    }, 1000);
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, am I correct to assume that "alert("Saved")" is where I am supposed to place my await function (setDoc)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.