Postcode Autocomplete
Why?
You don't want to have to type in a full postcode, so you can use the PostcodeAutocomplete component to autocomplete the postcode.
It also ensures that the postcode is valid.
How?
It fetches from an API we've created, and adds some extra functionality around an Ant Design Select component.
The main work is done in the fetchSuggestedPostcodes method:
const API_URL = 'https://geo-gql.now.sh/api'
const QUERY = `
query VenuesGetPostcode($postcode: String!) {
postcode {
suggest(prefix: $postcode) {
id
coordinates {
lat
lon
}
names {
laua
ward
}
}
}
}
`
const getPostcodeSuggestions = async (postcode) => {
const res = await fetch(
`${API_URL}?query=${QUERY}&variables=${JSON.stringify({ postcode })}`
)
const { data, errors } = await res.json()
return { data, errors }
}
const fetchSuggestedPostcodes = (props) => {
const { searchText } = props
if (searchText.length > 8) {
return Promise.resolve().then(() => {
throw new Error('Postcode Invalid')
})
} else if (searchText) {
return getPostcodeSuggestions(searchText).then((data) => {
console.log({ data })
if (data.data !== null) {
return data.data.postcode.suggest
} else {
throw new Error('Postcode Invalid')
}
})
}
}
This API will need to be updated to reflect new postcodes (e.g. people with new houses). Instructions on how to do that are here.
