The problem i am encountering is that i started a project , and i build the entire API call using axios
. Since i am in Nuxt 3
, i am trying to convert it to useFetch
. I am encountering a problem , and one is that when i reload the page , the data is not fetched again when i am using useFetch
.
This is my ApiService.js
(converted to useFetch
) :
import { useUserStore } from "~/store/user";
import qs from "qs";
class ApiService {
constructor(baseURL) {
this.baseURL = baseURL;
}
async apiRequest(method, url, data = null, options = {}, returnData) {
const store = useUserStore();
const requestUrl = `${this.baseURL}/${url}`;
const params = options.params ? `?${qs.stringify(options.params, { arrayFormat: 'comma' })}` : '';
try {
// Make the request using useFetch
const { data: responseData, error, status } = await useFetch(`${requestUrl}${params}`, {
method,
body: data,
credentials: options.withCredentials ? 'include' : 'omit',
headers: {
'Content-Type': 'application/json',
},
});
if (error.value) {
// Handling specific error statuses based on error.value
const errorStatus = error.value.response?.status || 500;
const errorReturnObj = {
status: errorStatus,
message: error.value.response?._data || error.value.message,
};
// Handling specific error codes
if (errorStatus === 401) {
console.error("Expired token");
store.showSnackbar("Token-ul a expirat/Access neautorizat!");
navigateTo('/user/logout');
} else if (errorStatus === 400) {
return returnData ? errorReturnObj : -2;
} else if (errorStatus === 515) {
return returnData ? errorReturnObj : -3;
} else if (errorStatus === 404) {
return returnData ? errorReturnObj : -4;
}
console.error(error.value.message || error.value.response?.status);
return 0;
}
console.log("data parameter",data)
console.log("responseData",responseData.value)
// Success response handling
const returnObj = {
status: status,
message: responseData.value
};
if (returnData === null) {
return returnObj;
}
return returnData ? responseData.value : 1;
} catch (error) {
console.error(error);
return 0;
}
}
get(url, returnData = false, isBlob = false, isAnonymous = false, params = {}) {
const options = {
params,
...(isAnonymous ? { withCredentials: false } : { withCredentials: true }),
};
return this.apiRequest("GET", url, null, options, returnData);
}
post(url, data, returnData = false, isAnonymous = false) {
const options = isAnonymous ? {} : { withCredentials: true };
return this.apiRequest("POST", url, data, options, returnData);
}
put(url, data, returnData = false, isAnonymous = false) {
const options = isAnonymous ? {} : { withCredentials: true };
return this.apiRequest("PUT", url, data, options, returnData);
}
delete(url, data = null, returnData = false, isAnonymous = false) {
const options = isAnonymous ? {} : { withCredentials: true };
return this.apiRequest("DELETE", url, data, options, returnData);
}
}
export default ApiService;
This is Products.js
:
import ApiService from "./ApiService"
class ProductsService extends ApiService{
constructor(){
super("http://localhost:5043/api/product")
}
/**
* @param {int?} pageNumber [The page number of with the current products]
* @param {Array<string>} productTypes [The array of product types to filter]
* @param {Array<string>} colorTypes [The array of color types to filter]
* @param {Array<string>} widthRange [The array of product dimensions width to filter]
* @param {Array<string>} heightRange [The array of product dimension height to filter]
* @param {Array<int>} priceRange [The array of product price to filter]
* @param {boolean} reverseFace [The type of reverse face (true or false)]
* @returns {List} [The list with a limit of 15 products]
*/
getProductsForUsers(pageNumber , productTypes , colorTypes, productDimensions, productPrice , productReverseFace, currency){
const params = {
productTypes,
colorTypes,
productDimensions,
productPrice,
productReverseFace
}
return this.get(`paginated/${pageNumber}/${currency}` , true , false , true , params)
}
/**
* @param {NONE}
* @returns {Object
* {
* filterColors : IMutableHashSet(ReadOnly),
* filterProductTypes : IMutableHashSet(ReadOnly)
* }}
* [The class with the filter options - color and productTypes]
*/
getFilterOptions(currency = "RON"){
return this.get(`filterOptions/${currency}` , true , false , true)
}
/**
* @param {String} productCode [The product code]
* @param {String} productType [The type of the product]
* @param {String} currency [The current currency : RON or EUR]
*
* @returns {Object{
* - integer : 1 or 0 (depends on succes)
* - productData : class (null if product has not been found )
* }}
*/
getProductData(productCode , productType, currency){
console.log('IN PRODUCTS.JS',this.get(`${productCode}/${productType}/${currency}` , true , false, true))
return this.get(`${productCode}/${productType}/${currency}` , true , false, true)
}
/**
* @param {FormData} form [The form with the review info]
* @returns {KeyValuePair<int,string>} [The info about the succefullness of the request]
*/
postProductReview(form){
return this.post('postReview' , form , false , false);
}
}
export default new ProductsService()
And here i call getProductData
in my .vue
file:
const getProductData = async () => {
const response = await productService.getProductData(productCode,productType , selectedCurrency.value);
console.log("IN GET PRODUCT DATA" , response)
if(response === -4){
navigateTo(localePath('/error/notFound'))
}else if(response === -2){
navigateTo(localePath('/error/generalError'))
}
Object.assign(product.value , response)
console.log(product.value)
if (product.value.culoriProdus && product.value.culoriProdus.length > 0) {
// Set the default color as the first color available
selectedColor.value = {
name : product.value.culoriProdus[0].numeCuloareDto,
colorCode: product.value.culoriProdus[0].codCuloareDto
};
activeButtonColors.value = 0;
filterImagesByColor(selectedColor.value.name);
}
if(product.value.dimensiuniProdus && product.value.dimensiuniProdus.length > 0){
dimensionsLength.value = product.value.dimensiuniProdus.length;
selectedDimension.value = {
width: product.value.dimensiuniProdus[0].lungimeDto,
height: product.value.dimensiuniProdus[0].latimeDto,
price : product.value.dimensiuniProdus[0].pretDto,
priceDiscount: product.value.dimensiuniProdus[0].pretRedusDto
}
activeButtonDimensions.value = 0;
}
if(product.value.reviewsProdus){
reviewsLen.value = product.value.reviewsProdus.length
}
}
/* missing code */
onBeforeMount(async () => {
getCurrentLocale()
await getProductData()
})
</script>