I am a beginner using Vue 3, to learn it I am developing a simple weather webapp using OpenWeatherMap API. I have added multilanguage support using vue-i18n library and everything works fine. But there is only one issue, the weather description language that OWM API returns depends on the lang
parameter passed in the request. Hence, even if the app language is fully reactive and changes when I switch the language, that weather description is not updating, that is normal because it would need to re-request the API with the proper lang
value. But I can’t figure out how to do that. How can I achieve re-rendering that component in order to get the right language in the description returned by the API?
Below is my component with the relevant code:
<script setup>
import axios from "axios";
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const i18nLocale = useI18n();
const route = useRoute();
const getWeatherData = async () => {
const langapi = i18nLocale.locale.value.substring(0, 2);
try {
const weatherData = await axios.get(`https://api.openweathermap.org/data/3.0/onecall?lat=${route.query.lat}&lon=${route.query.lng}&exclude={part}&appid=${myapikey}&units=metric&lang=${langapi}`);
// cal current date & time
const localOffset = new Date().getTimezoneOffset() * 60000;
const utc = weatherData.data.current.dt * 1000 + localOffset;
weatherData.data.currentTime =
utc + 1000 * weatherData.data.timezone_offset;
// cal hourly weather offset
weatherData.data.hourly.forEach((hour) => {
const utc = hour.dt * 1000 + localOffset;
hour.currentTime =
utc + 1000 * weatherData.data.timezone_offset;
});
await new Promise((res) => setTimeout(res, 500));
return weatherData.data;
} catch (error) {
console.log(error);
}
}
const weatherData = await getWeatherData();
// ...
</script>
<template>
// ...
<p class="capitalize">
{{ weatherData.current.weather[0].description }}
</p>
// ...
</template>
I guess I should refresh the component in order to do another call to the API with the right lang parameter, or to more simply re-invoke the getWeatherData
function, but I can’t figure out how to do that.