A Simple way to get User’s Country, State & City Information in VueJS.

Ogunmefun Anjolaoluwa
4 min readOct 22, 2021
Photo by Capturing the human heart. on Unsplash

A good number of applications or websites you visit daily directly or indirectly make use of your location.

There are a couple of reasons why you as a developer would need your user’s location. For instance if;

  1. you want to personalize your user’s experience when they browse your website or application.
  2. you want to show tailored promotions.
  3. you want to change the language of your site based on where your users are coming from.
  4. you want to gather information on your application coverage
  5. you do not yet cater to certain locations.

These (just to mention a few) are valid reasons to request a user’s country, state, and/or city.

Choose the right API

From the research I carried out on the available APIs out there, I was able to come up with two amazingly simple and free APIs.

1. Universal tutorial API: This is a free rest API with tutorials also on their official website. Before consuming the API you have to generate an authorization token which will be passed with every call as a Bearer token. The only setback with this API is that the generated authorization token expires every 24 hours. Meaning that you always have to regenerate the token after 24 hours.

That is too much stress that can be avoided which leads me to my preferred choice;

2. CountryStateCity API: This is also free and comes with user-friendly documentation and demo. To get started, you will need to request an API key from their official website and you’re good to go. The key generated doesn’t expire! Amazing right?

Moving forward, I’ll be using the Countrystatecity API.

To follow along, all you need is a Vue app up and running. That out of the way, let's get right into it.

From the API documentation here, the example given is replicated below:

var headers = new Headers();
headers.append("X-CSCAPI-KEY", "API_KEY");
var requestOptions = {
method: 'GET',
headers: headers,
redirect: 'follow'
};
fetch("https://api.countrystatecity.in/v1/countries", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

where “API_KEY” is your key that was sent to your mail.

To avoid having to declare the variable headers and requestOptions for every API call, I created them as global variables in the main.js file. By doing that I have access to the requestOptions variable through this.$requestOptions.

Add the following to your main.js file

app.config.globalProperties.$headers = new Headers();app.config.globalProperties.$headers.append(
"X-CSCAPI-KEY",
"YOUR API_KEY HERE"
);
app.config.globalProperties.$requestOptions = {
method: "GET",
headers: app.config.globalProperties.$headers,
redirect: "follow",
};

This part is optional, you can make your API calls just as seen in the example but it’s just good practice to not repeat yourself.

Create the User Interface

For this article, we will be going with a basic interface of field inputs just as seen below.

The template of the Vue app looks like this;

The explanation of the template is simply;

For the ‘Select Country’ input field:

We are binding the value of the selected option to the data property- selectedCountry using v-model and when an option is selected, we call the method- selectCountry.

Then for the options, we loop through the list of countries (gotten from the API call) using the v-for directive, binding each country’s ID as a key, passing the selected country object as a value, and finally displaying the name key in the country object via country.name

The same applies to ‘Select State’ and ‘Select City’ with the only difference being that we disable either or both fields that return an empty list (via the :disabled). By this I mean if a selected country doesn't have any state, the state field is disabled. likewise, if a selected state doesn't have any city, the city field is disabled. Automatically, if a country doesn't have states, it’s not expected to have cities hence both select state and select city fields are disabled.

Write The Methods

The script part of your file should look something like this;

We see the data properties we are returning all holding the data their name suggests.

By default, the user is expected to be presented with a list of countries to select from hence we make a call to fetch the list of all countries when the component is mounted.

For the selectCountry method:

We initially set the states and cities array to empty arrays so that for instances where state and city have been previously selected, upon selecting a new country, the states and cities array are cleared to accommodate the change in values.

Afterward, we check if the countries array is not empty and that a country was indeed selected then we make a call to fetch the states of the selected country and assign the returned data to the states data property. If an empty array is returned from the call to fetch states (meaning that the selected country has no states), the hasStates data property is set to false which in turn disables the “Select State” input field.

The same goes for selectState method with the only difference being that we are making a call to check for cities. while the selectCity method basically logs the selected city to the console.

You can further decide how you want to consume the data provided by the user but basically, this helps you fetch the necessary data. You can definitely also work on a better styling just as you wish.

Pretty straight forward right? I hope you found this article useful.

--

--

Ogunmefun Anjolaoluwa

The little girl who grew to become a Frontend Developer, who’s not so little anymore