Fetch All Countries in a React.js App in any Language
Tags: javascript, react, webdev, tutorial
Published: 2022-05-10 14:39:10

Web applications have been extremely functional because of the idea that they are available globally. However, this pro has some cons since some information may get lost in translation in different parts of the world. 
Web applications have been extremely functional because of the idea that they are available globally. However, this pro has some cons since some information may get lost in translation in different parts of the world.


## What we will be building 

This post will discuss using a Locale service API to customize our application based on our preferred language.

**GitHub URL**
https://github.com/Iheanacho-ai/appwrite-countries

## Prerequisites

To get the most out of this project, we require the following:

- A basic understanding of CSS, JavaScript, and React.js.
- Docker Desktop is installed on your computer, run the `docker -v` command to verify if we have docker desktop installed, if not, install it from the [Get Docker documentation](https://docs.docker.com/get-docker/)
- An [Appwrite](https://appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba&utm_campaign=hackmamba-blog) instance running on your computer, check out [this article](https://dev.to/hackmamba/create-a-local-appwrite-instance-in-3-steps-19n9?utm_source=hackmamba&utm_medium=hackmamba) to understand how to create a local Appwrite instance, we will use the [Appwrite Locale API](https://appwrite.io/docs/client/locale??utm_source=hackmamba&utm_medium=blog&utm_campaign=react-fetch-countries) to handle translating countries into different language.

## Setting up our React.js app

We navigate to our preferred directory to create a React.js application using this command:

```bash
npx create-react-app <name of our app>

```
After creating our app, we change the directory to our project and start a local development server with:

```bash
cd <name of our project>
npm run start

```
To see the app, we go to https://localhost:3000

![React Index page](https://paper-attachments.dropbox.com/s_D2E5BC9B38347E8D57CD4461AFFDE366C2A526B69F66F91BFA9637322C3A4BD9_1624279658117_React+app.PNG)

## Installing Appwrite

[Appwrite](https://appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba&utm_campaign=hackmamba-blog) is an open-source, end-to-end, back-end server solution that allows developers to build applications faster.

To use Appwrite in our Next.js application, we install the Appwrite client-side SDK for web applications.

```bash
npm install appwrite
```

## Creating a new Appwrite project

During the creation of the Appwrite instance, we specified what hostname and port we see our console. The default value is [localhost:80](http://localhost/).

We go to [localhost:80](http://localhost/) and create a new account to see our console.

On our console, there is a **Create Project** button. Click on it to start a new project.

![Appwrite console](https://paper-attachments.dropbox.com/s_314B50E78D2533608F0DEE9BE97FEF3C5B7916B2F8CAC55559F4DCA3A07D86F6_1648400276700_Screenshot+64.png)


Our project dashboard appears once we have created a project. At the top of the project page, there is a **Settings** bar. Click it to access the **Project ID** and **API Endpoint**.  


![Appwrite Settings Bar](https://paper-attachments.dropbox.com/s_D2AD994B65B69E06BE768F5E2E074F441F6AB26C0DDBAB8EFDA877675651E273_1650011975410_Screenshot+113+-2.png)


We copy the **Project ID** and **API Endpoint**, which we need to initialize the Appwrite Web SDK.

![Appwrite Settings Page](https://paper-attachments.dropbox.com/s_D2AD994B65B69E06BE768F5E2E074F441F6AB26C0DDBAB8EFDA877675651E273_1650012002211_Screenshot+114.png)


In our `App.js` file, we initialize a new Appwrite instance with the following.

```jsx
    import {Appwrite} from "appwrite";
    import {useEffect, useState } from "react";
    
    const App = () => {
    
        // Init our Web SDK
        const sdk = new Appwrite();
        sdk
        .setEndpoint('http://localhost/v1') // our API Endpoint
        .setProject(projectID) // our project ID
        ;
    
        return(
          <div>Hello World!</div>
        )
    }
    
    export default App;
```

## Creating the select list application.

Our `App.js` file will consist of buttons that will allow users to select a language of their choice and a select list to display the countries in the language chosen by the user.

```jsx
    import {Appwrite} from "appwrite";
    import {useEffect, useState } from "react";
    
    const App = () => {
    
        // Init our Web SDK
        const sdk = new Appwrite();
        sdk
        .setEndpoint('http://localhost/v1') // our API Endpoint
        .setProject(projectID) // our project ID
        ;
    
         return (
          <div className="App">
            <div className="app-container">
              <h2>Choose your Language</h2>
              <div className="button-container">
                  <button id "button">English</button>
              </div>
              <select name="countries" id="countries-list">
                <option value="country">Country</option>
              </select>
            </div>
            
          </div>
        );
    }
    
    export default App;
```

**Selectively rendering our list** 

The [Appwrite Locale API](https://appwrite.io/docs/client/locale??utm_source=hackmamba&utm_medium=blog&utm_campaign=react-fetch-countries) allows us to collect country information in any desired language by switching locales. [View the list of available locales](https://github.com/appwrite/appwrite/blob/master/app/config/locale/codes.php) to know what languages are supported by the Appwrite Locale API.

In our `App.js` file, we create two state variables. One state variable will hold the information about the buttons that select a user's preferred language, and the other will contain the list of countries.

```jsx
    const [countries, setCountries] = useState(["country"])
    const [buttons, setButtons] = useState([
      {
        name: "English",
        id: "en"
      },
      {
        name: "Arabic",
        id: "ar"
      },
      {
        name: "Chinese - China",
        id: "zh-cn"
      },
      {
        name: "Slovenian",
        id: "sl"
      },
      {
        name: "Turkish",
        id: "tr"
      },
    ])
```

The `buttons` object has two fields. The `name` field holds the language we will fetch our countries in, and the `id` field is the Appwrite locale to get the language.

Next, in our `App.js` file, we create a `getCountries` function that runs anytime we click one of the buttons.

```jsx
    const getCountries = async (e) => {
      try {
        setCountries([])
        let buttonId = e.target.id
        sdk.setLocale(buttonId)
        let promise = await sdk.locale.getCountries()
        promise.countries.map((country)=> setCountries(prevArray => [...prevArray, country.name])) 
      } catch (error) {
        console.log(error)
        
      }
    }
```

The `getCountries` function in the code block above does the following:

- Clears out the information in the `countries` array variable
- Collects the ID on the clicked button
- Uses the ID to switch locale, using Appwrite’s `setLocale` method
- Updates the `countries` array with our response
- Logs any error we encounter to the console

Next, in our `App.js` file, we loop through the `buttons` and `countries` array variables to create multiple buttons and select options.

```jsx
    return (
      <div className="App">
        <div className="app-container">
          <h2>Choose your Language</h2>
          <div className="button-container">
            {
              buttons.map(({name, id}) => (
                <button id={id} onClick={getCountries}>{name}</button>
              ))
            }
          </div>
          <select name="countries" id="countries-list">
            {
              countries.map((country) => (
                <option value="country">{country}</option>
              ))
            }
          </select>
        </div>
        
      </div>
    );
```
The code block above does the following:

- Loop through the `buttons` array variable, destructuring each object pass in the `id` and the `name` fields to each button we create
- Pass the `getCountries` function to the `onClick` event listener on the buttons
- Loop through the `countries` variables to create multiple select options

Here is our `App.js` file.


https://gist.github.com/Iheanacho-ai/b4a1a5a5a88172f538e745b95176def0

Here is how our application looks. Click on a different button to have the countries listed in a different language.


![React Countries Application](https://paper-attachments.dropbox.com/s_D2AD994B65B69E06BE768F5E2E074F441F6AB26C0DDBAB8EFDA877675651E273_1650012519488_Screenshot+183.png)

## Conclusion

This article discussed using the [Appwrite](https://appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba&utm_campaign=hackmamba-blog) Locale API to selectively render a list of countries depending on what language we selected. We can use the select list logic for large-scale apps to help developers build in different languages in other parts of the world to communicate better.

## Resources

Here are some resources that might be helpful:

- [Locale API](https://www.dropbox.com/scl/fi/6as1jvfvh26zn7mcmkmcy/Fetch-all-countries-in-a-React.js-app-in-any-language.paper?dl=0&rlkey=11kvo66p5mmd1vu412bieaion)
- [Automating File Upload and sharing](https://cloudinary.com/blog/automating_file_upload_and_sharing?utm_source=appwrite&utm_medium=affiliate&utm_term=hackmamba)
- [What is Appwrite and How to use it Efficiently](https://dev.to/noviicee/what-is-appwrite-and-how-to-use-it-efficiently-3o1m)