Async content in Modal
Published: 2023-10-13 12:49:11

How to put the result of a fetch content in a modal ?

Here my solution :

```js
const Content = {};

Content["apropos"] = () => `
    <div style="text-align:center">
      Demoing filling modal content with fetch results.
      <br />
      Get some Chuck Norris quotes
    </div>
`

Content['cnquotes'] = async () => {
    const resp = await fetch('https://api.chucknorris.io/jokes/random')
    const json = await resp.json()
    return `
      <div class="cnquotes">
        ${json.value}
      </div>
    `
}

window.State = {
  content: null,
  isOpen: false,
  openDialog: function(key){
    State.content = Content[key]
    State.isOpen = true;
    view()
  },
  closeDialog: function(){
    State.isOpen = false;
    view()
  }
}

async function view () {
  var modalCls =  State.isOpen 
    ? "modal modal-shown"  
    : "modal modal-hidden"
  modal.innerHTML =  `
    <div class="${modalCls}">
      <div class="modal-content">
        <div style="text-align:right" onclick="State.closeDialog()">
          <span class="modal-close">close</span>
        </div>
        <p>${await State.content()}</p>
      </div>
    </div>
  `
}

triggerModal.addEventListener("click", function (e) {
  var modal  = e.target.getAttribute("modal")
  modal && State.openDialog(modal)
})

```

You can play with it here : [Async Modal Content](https://flems.io/#0=N4IgtglgJlA2CmIBcA2ADAOgBwBYA0IAZhAgM7IDaoAdgIZiJIgYAWALmLCAQMYD21NvEHIQAHigQAbgAJoAXgA64PlFqxlAPjEB6SVM2LqRidMPUZMsSwCMmgIKkAntR4yAsqvUyAwgKGCurbmlkaWprIKymwAThAA5vHwMZ5qGiAhllYARgCubGwClmBesEogtAAOMXyVfKTKMplZlvbZfPlhWbp5BQLNOfmFFjIlaeU81ACOuXxCDSBNXS2+LLk8ANYyAHJ8MXENI+E6vcOaLV26+uZXZkZG3CCk8Ag8bBAC5EwAzEgATABWEAAXzwNHojGYACtyLx-MI2KJ+NRSGxfPDBDJ5DJgMCANz3ah+QQIijKKo1OoLAC6WJkAAoAJRY84AA2WVn0MlRTgQ5SEAA82ABadQJahIHgI5JaDmWAAi8BKEGo8RkxFgsBVarG3mRATRAHcIGwWOr4GweGaYvBSLlYGxSBg5TkYjIdANLABxC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