I am struggling to properly create and retrieve data from a "useFetch" composable. My fetch composable looks like this:
import { reactive, Ref } from "vue";
import axios from "axios";
export default function useFetch(
requestId: Ref<number>,
fetchType: string,
) {
const queryId = requestId;
const data: any = reactive([]);
const fetchRequest = fetchType;
switch (fetchRequest) {
case "storeInfo":
fetchStoreInfo();
break;
}
function fetchStoreInfo() {
const infoQuery = `SELECT * FROM t_store_info WHERE ss_store_id = ${queryId.value}`;
axios
.post(`url`, query, {
headers: {
"content-type": "text/plain",
},
})
.then((response) => {
data.value = response.data[0];
})
}
return { data };
}
And my main:
let requestId = ref(0);
let storeData = reactive([]);
async function getStoreInfo() {
try {
storeData = useFetch(requestId, "storeInfo");
} finally {
console.log(storeData); //this prints to console the object with all the right data inside
console.log(storeData.data); // prints same as above, but unable to go deeper from here
console.log(storeData.data.store_id); //this is undefined
console.log(storeData.data[0]); // this is undefined
console.log(storeData.data.value); // this is undefined
console.log(storeData.data[0].value); //this throws an error
}
}
The fetched object structure looks like this, if it helps:
{
"storeId": 1,
"storeName": "Store Name Inc",
"storeAddress": "address here",
}
I am trying to access data from the storeData object like storeData.storeName, but it is always undefined. How do I access the properties properly when they're retrieved from a composable? What's the right way to retrieve fetched data from a composable?
My question was closed as duplicate but the question regarding asynchronous functions doesn't seem to apply here.
I am able to access the data after the call, so the data itself isn't undefined, I just can't seem to access the properties of the data inside. The properties are undefined. When I console log the data object itself, I see the data all there, as illustrated above.
I have deliberately went to the link provided and tried their methods of using async/await and promises to ensure the data is filled and exists before calling it. It still causes the same issue where the data object is there, and if I log the object I see its properties, I'm just using the wrong method of logging/accessing just the data properties. I'm sure the answer must be very simple and I'm just using the wrong syntax to access the property.