23 Aug 2024

I have been learning how to use GraphQL to link my applications to a database. I found this tutorial by Web Dev Simplified, but some of the content was outdated. After doing some research, I created this updated version.
In this tutorial, we’ll build a simple React app that allows users to select a continent from a dropdown menu and display the corresponding countries. We’ll use Vite to set up the project and GraphQL to fetch data dynamically.
First, create a new React project using Vite and start the development server:
npm create vite@latest continent-country-selector
cd continent-country-selector
npm install
npm run devVite provides a faster and more efficient development experience compared to tools like Create React App.
Next, set up the basic structure of your App.jsx component. This component will manage state for continents, the selected continent, countries, and UI visibility.
We’ll use the fetch API to send GraphQL queries to https://countries.trevorblades.com/. Start by creating a reusable fetchGraphQL function:
Fetch the list of continents when the component mounts using useEffect, and store the result in state.
Once fetched, render the continents inside a dropdown menu:
When a user selects a continent, fetch the corresponding countries using another useEffect hook:
Finally, render the list of countries below the dropdown:
In this tutorial, we built a simple React app using Vite that allows users to select a continent and view the corresponding countries. By leveraging GraphQL and the fetch API, we dynamically updated the UI based on user input.
If you want to explore the full project, here’s the complete source code on GitHub.
