Reputation: 3228
i'm working with a Vue3 project with Pinia and i need to perform an async call in the state function.
I have a Pinia store made in this way to manage login
export const useAuthStore = defineStore({
id: "auth",
state: () => ({
user: JSON.parse(localStorage.getItem("user")),
returnUrl: null,
}),
actions: {
async login(form) {
ApiService.post("/login", form)
.then((res) => {
if (res.data.result) {
const user = {};
user.username = res.data.username;
const appStore = useAppStore();
const macaddress = appStore.mac.value;
user.macaddress = macaddress;
this.user = user;
localStorage.setItem("user", JSON.stringify(user));
router.push(this.returnUrl || "/admin");
} else {
alert("auth error");
}
})
.catch((error) => {
console.log(error);
});
},
logout() {
this.user = null;
localStorage.removeItem("user");
router.push("/");
},
},
I need to take the macadress value from a composable script, useAppStore which is made in this way:
import { ref } from "vue";
import { ApiService } from "@/services";
export default function useAppStore() {
const mac = ref(null);
const getMacAddress = async () => {
const response = await ApiService.get("/getmac");
mac.value = response.data.message;
};
getMacAddress();
return { mac };
}
When i do the logo, the appStore.mac.value
is always null. I cannot understand how to wait for it in the store script
Upvotes: 0
Views: 264
Reputation: 14649
You must await the result of getMacAddress()
, and then must also await useAppStore()
. See my updated code with comments below:
composable
export default async function useAppStore() { // is now async
const mac = ref(null)
const getMacAddress = async () => {
const response = await ApiService.get("/getmac");
mac.value = response.data.message;
}
await getMacAddress() // now uses await
return { mac }
}
store
ApiService.post("/login", form)
.then((res) => {
if (res.data.result) {
const user = {};
user.username = res.data.username;
const appStore = await useAppStore(); // now uses await
...
Upvotes: 0