The idea is to allow the user to enter the postcode (e.g. '2000') and then fetch the postcodes with locality from the database and present them for selection
Created
February 6, 2024 13:52
-
-
Save JavascriptMick/aead5e0d16dac6f1a79339322c8b3d21 to your computer and use it in GitHub Desktop.
Nuxt3 postcode selector component with background fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div class="relative"> | |
<input | |
v-model="inputValue" | |
@keyup.prevent="fetchData" | |
type="text" | |
placeholder="Enter postcode" | |
class="border border-gray-300 rounded p-2 w-full" /> | |
<div | |
v-if="postcodesForSelection.length > 0 && showDropdown" | |
class="absolute z-10 border border-gray-300 rounded bg-white w-full mt-1"> | |
<select | |
v-model="selectedPostCode" | |
class="p-2 w-full" | |
:size="postcodesForSelection.length" | |
@change="selectPostCode"> | |
<option | |
v-for="(item, index) in postcodesForSelection" | |
:key="index" | |
:value="item"> | |
{{ item }} | |
</option> | |
</select> | |
</div> | |
</div> | |
</template> | |
<script setup lang="ts"> | |
import { ref, watch } from 'vue'; | |
const { $client } = useNuxtApp(); //I'm using TrpC so I'm retrieving the trpc $client | |
const props = defineProps({ | |
modelValue: String | |
}); | |
const emit = defineEmits(['update:modelValue']); | |
const inputValue = ref(props.modelValue); | |
const postcodesForSelection: globalThis.Ref<string[]> = ref([]); | |
const selectedPostCode = ref(''); | |
const showDropdown = ref(false); | |
watch( | |
() => props.modelValue, | |
newValue => { | |
inputValue.value = newValue; | |
} | |
); | |
const fetchData = async () => { | |
if (inputValue.value && inputValue.value.length === 4) { | |
//again, i'm using Trpc with a postcode router so I'm grabbing my data from that. You may want to fetch from a restful endpoint or whetever | |
const result = await $client.postcode.getByPostCodeOrPartial.useQuery({ | |
postCodeOrPartial: inputValue.value | |
}); | |
postcodesForSelection.value = result.data.value.postCodes.map( | |
postcode => | |
`${postcode.locality}, ${postcode.state} ${postcode.postcode}` | |
); | |
showDropdown.value = true; | |
} else { | |
postcodesForSelection.value = []; | |
showDropdown.value = false; | |
} | |
}; | |
const selectPostCode = () => { | |
emit('update:modelValue', selectedPostCode.value); | |
inputValue.value = selectedPostCode.value; | |
showDropdown.value = false; | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment