Skip to content

Instantly share code, notes, and snippets.

@devinschumacher
Created September 9, 2024 21:36
Show Gist options
  • Save devinschumacher/87e7b62bb4ee7dfe7cf7220c7f0e324f to your computer and use it in GitHub Desktop.
Save devinschumacher/87e7b62bb4ee7dfe7cf7220c7f0e324f to your computer and use it in GitHub Desktop.
How To Use External Api With Dynamic Filterable Search Component
title tags
How To Use External Api With Dynamic Filterable Search Component
Nuxt
useRuntimeConfig
nuxt.config.ts
typescript
index.ts
NuxtUI
SOP

Parts:

  1. nuxt.config.ts
  2. components/CitiesLookup.vue
  3. app.vue
  4. types/index.ts
  5. External API

nuxt.config.ts

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'
    }
  }
})

components/CitiesLookup.vue

<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>

app.vue

<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>

types/index.ts

export { };

declare global {
    type CityData = {
        name: string
        lat: number
        lon: number
        country: string
        state: string
    }
}

Result:

A searchable select menu that filters as you type!

Screenshot 2024-09-09 at 14 34 44

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment