I have a dedicated external .js file designed to retrieve data from the backend depending on the website's locale. Check out the code snippet below:
import { ref } from "vue";
export function fetchData(section, key) {
// Making a GET request using fetch with error handling and headers
const headers = {
method: "GET",
headers: { "Content-Type": "application/json" },
};
const fetchedData = ref(null);
fetch(
"http://localhost:4000/api/" + section + "/?api-key=" + key,
headers
)
.then(async (response) => {
const data = await response.json();
// Checking for error response
if (!response.ok) {
// Retrieving error message from body or defaulting to response statusText
const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}
fetchedData.value = data;
})
.catch((error) => {
console.error("There was an error!", error);
return error;
});
return fetchedData;
}
This is how I'm calling the fetchData function in my .vue file:
<script setup>
import { fetchData } from "../../utils/universal-fetch";
import { ref, watch } from "vue";
import { useStore } from "../../stores/language.js";
import { useI18n } from "vue-i18n";
import AOS from "aos";
const store = useStore();
const { locale } = useI18n({ useScope: "global" });
const fetchedData = ref(fetchData("homeFirstSection", store.getLanguage));
AOS.init();
watch(
() => locale.value,
() => {
fetchedData.value = fetchData("homeFirstSection", store.getLanguage);
}
);
</script>
Upon creating/refreshing the page, the fetchData function successfully retrieves data from the backend. My current challenge is updating the fetchedData variable based on the selected locale when it changes.
Thank you!