External API Usage

Keenan Jones
4 min readJan 9, 2021

Hello, today I would like to walk through my process of using an external api while, writing a small weather application project. The reason for this article is to show how to implement apis within React.js. The Project is a small app to display weather data, that takes an input from the user about their location and displays local weather in that area. The app must contain: A button that says “Current Weather”, Use the geolocation api to get the user’s location, Use the openweathermap api to display weather for the location, and finally we must deploy the project.

The technologies I will be using will be: React as javascript frontend framework, the built-in Geolocation api, Openweathermap api and component styling with styled-components which is a node package for react and javascript. I will make a separate walk through for styling. But let’s begin this walkthrough with create-react-app.

npx create-react-app weatherApp
cd weatherApp
code .
npm start

Inside the src folder I will creating a components folder that will hold my react components. My most outer component that will be imported into the app.js will be my container. This will be a react functional component. I used a functional component because I will be using Hooks also. This is not a react or javascript tutorial this is a api usage tutorial. I’m sorry, but I’m not going into depth on how to use hooks.

My next component will be the LocationButton component that will hold my button and the callback function that will trigger when the button is clicked. The location button is also the first component that will use the styled component package. After this component I will be creating the WeatherCard that will display the information from the openweathermap api. This component will also implement the styled-component package, that I will be implementing in another article. So, stay tuned.

After constructing our folder and file structure, I want to take this time to explain the geolocation api that is built into your computer. The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information. The Geolocation API is accessed via a call to navigator.geolocation; this will cause the user’s browser to ask them for permission to access their location data. Geolocation.getCurrentPosition(): Retrieves the device’s current location. I created a button inside my LocationButton component, the component returns a div with a button inside the button will trigger a function. This function will invoke the geolocation api. If the api is allowed to receive the location details then the success function will run that will send the coordinates to my container component that will hold the state of the app. This is seen as props.setCoords().

const findme = () => {let success = (position) => {const latitude  = position.coords.latitude;const longitude = position.coords.longitude;props.setCoords(latitude, longitude)}let error = () => {console.log('Unable to retrieve your location')}if(!navigator.geolocation){console.log('Geolocation is not supported by your browser');}else{navigator.geolocation.getCurrentPosition(success, error);console.log(Loading...}}

After my coordinates are found and updated in the state then my fetch call to the openweather map api is called.

const [stateObject, setStateObject] = useState({coordinates: {},weather: {}})const setCoords = (lat, long) => {setStateObject({...stateObject, coordinates: {latitude: lat, longitude: long}})fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&units=imperial&appid=${apiKey}`).then(resp => resp.json()).then(data => setStateObject({coordinates: {latitude: lat, longitude: long}, weather: data}))}

Before explaining the weather api I have to go over the dot.env package. The purpose of this package is to load environment variables dynamically for your React applications created with CRA (Create-React-App). So API keys are stored in env files because we don’t want the public to have access to our keys. All you really need to do is create a .env file inside your project folder, The root folder and add .env to your gitignore file. Back to your .env file add the following lines to the top of your .env file.

REACT_APP_API_KEY=

That’s it for now. Now register for your api key by creating an account for openweathermap and navigating to the members section in the dropdown menu under your name. and generate a key in the right side of the scene. Add that key after the equal sign in the .env in quotes.

Now back to the container component in my setCoords now in the openweathermap api will explain where to make the fetch request out to, but you will include your api key. this is done by adding the following lines at the top of this file.

var apiKey = process.env.REACT_APP_API_KEY;

This line will allow you to use the api key you declared in your .env file inside of your fetch call.

fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&units=imperial&appid=${apiKey}`).then(resp => resp.json()).then(data => setStateObject({coordinates: {latitude: lat, longitude: long}, weather: data}))

And that’s it that's how you integrate an external api inside your react application.

Thanks for reading!

--

--