Skip to content
Advertisement

Why won’t my async call fire inside this Vue 3 component (using composition API)?

I’m trying to make an async call to fetch data from my Fauna database. But I can’t get the async call to fire.

Inside the setup() function I have console.log("Setup is working"); and that works as expected. It shows on page load.

Then inside the callApi async function I have console.log("callApi is working");. That async function is called on a button click event. But when clicking the button nothing happens. The function is not fired and nothing prints to the console.

What am I doing wrong?

<template>
  <div>
    <div class="mb-5">
      <button class="btn btn-primary mt-5" @click="callApi">
        Call API
      </button>
    </div>

    <div class="result-block-container">
      <div :class="['result-block', executed ? 'show' : '']">
        <h6 class="muted">Result</h6>
        {{ JSON.stringify(apiMessage, null, 2) }}
      </div>
    </div>
  </div>
</template>
import { defineComponent, inject } from "vue";
import { query as q, client } from "faunadb";

export default defineComponent({
  name: "Api",
  setup() {
    console.log("Setup is working"); //<---- THIS PRINTS TO CONSOLE ON PAGE LOAD
    const callApi = async () => {
      console.log("callApi is working"); //<---- THIS DOES NOT PRINT TO CONSOLE ON BUTTON CLICK
      const apiMessage = null;
      const executed = false;
      const auth = inject("Auth");
      const accessToken = await Auth.getTokenSilently();
      try {
        const client = new Client({ secret: accessToken });
        const { Paginate, Documents, Collection, Lambda, Get, Var } = q;

        const data = await client.query(
          q.Map(
            Paginate(Documents(Collection("stores"))),
            Lambda(["storeRef"], Get(Var("storeRef")))
          )
        );

        console.log(data);
        apiMessage = data;
        executed = true;
      } catch (e) {
        console.log(e);
        apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
      }
    };
  },
});

Advertisement

Answer

Usage with Templates

If setup returns an object, the properties on the object can be accessed in the component’s template

You just need to return the properties you want available to your template

return {
  callApi
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement