I am trying to use createFetch to create a pre-configured useFetch function. Later, in a Pinia store action I use await to invoke the function to call an API. The defining functions is as follows:
import { createFetch } from "@vueuse/core";
import { ref } from "vue";
const token = ref("");
export function defineServer(baseUrl, options = {}) {
return createFetch({
baseUrl,
options: {
...options,
beforeFetch(ctx) {
ctx.options.headers.Authorization = token.value;
return ctx;
},
afterFetch(ctx) {
const header = ctx.response.headers.get("Authorization");
token.value = header ? header : "";
return ctx;
},
},
fetchOptions: {
mode: "cors",
},
});
}
The Pinia store code is as follows:
import { defineStore } from "pinia";
import { defineServer } from "@/js/poster.js";
const authServer = defineServer("https://localhost/auth-server");
export const useAuthStore = defineStore("auth", {
state: () => {
return {
signedIn: false,
mode: "Login",
user: { email: "", firstName: "", lastName: "" },
};
},
getters: {
credential(state) {
if (state.signedIn) {
return `${state.user.firstName} ${state.user.lastName} (${state.user.role})`;
} else return "Guest";
},
},
actions: {
async signin() {
const data = await authServer("login")
.post({
email: "[email protected]",
password: "password",
})
.json().data;
this.signedIn = true;
console.log(data);
const credentials = data.msg.split("|");
this.user.email = credentials[0];
this.user.firstName = credentials[1];
this.user.lastName = credentials[2];
this.user.role = credentials[3];
return;
},
}
}
Although I'm using await to call authServer, it returns immediately and consequently the data is undefined. I can see the call does return the expected data but too late; What should I be doing to make the call properly async?
The json() function returns a Promise that needs to be awaited separately. You'll need to split your current authServer call into two statements: