title | tags | |||||||
---|---|---|---|---|---|---|---|---|
How To Use External Api With Dynamic Filterable Search Component |
|
nuxt.config.ts
components/CitiesLookup.vue
app.vue
types/index.ts
- External API
export default defineNuxtConfig({
compatibilityDate: '2024-04-03',
devtools: { enabled: true },
modules: [
"@nuxtjs/google-fonts",
"@nuxt/ui"
],
googleFonts: {
families: {
Roboto: [
100,300,400,700,900
]
}
},
runtimeConfig: {
public: {
weatherApiKey: '1f6ec271f3da959c1db1575514f66264'
}
}
})
<template>
<USelectMenu
v-model="activeCity"
:searchable="citiesLookup"
placeholder="Search for a city.."
/>
</template>
<script setup lang='ts'>
const config = useRuntimeConfig();
const apiKey = config.public.weatherApiKey;
const activeCity = ref();
const citiesLookup = async (query: string) => {
if (!query) return
const response: Array<CityData> = await $fetch(
`http://api.openweathermap.org/geo/1.0/direct?q=${query}&limit=5&appid=${apiKey}`
)
return response.map(city => ({
...city,
label: `${city.name}, ${city.country}`
}))
}
</script>
<template>
<div class="min-h-screen py-4 bg-slate-100 dark:bg-slate-800">
<u-container>
<u-card>
<h1 class="text-3xl text-center">h1!</h1>
<p class="">Search for weather by city</p>
<CitiesLookup/>
</u-card>
</u-container>
</div>
</template>
<script setup lang='ts'>
async function citiesLookup(query: string) {
// get access to the runtimeConfig object in nuxt.config.ts
const config = useRuntimeConfig();
// get the API KEY from the runtimeConfig object
const apiKey = config.public.weatherApiKey;
const response = await $fetch(
`http://api.openweathermap.org/geo/1.0/direct?q=${query}&limit=5&appid=${apiKey}`
);
return response;
}
// test out the API call & display the response in the console
const data = await citiesLookup('seattle')
console.log(data)
</script>
export { };
declare global {
type CityData = {
name: string
lat: number
lon: number
country: string
state: string
}
}
A searchable select menu that filters as you type!