Welcome back to this tutorial on using React and TypeScript to build client-side web apps. In Part 1 we covered:
- Boot-strapping an app with
- Using React with TypeScript
- React Hooks
In this post we will complete the tutorial by:
- Integrating the Open Weather API
- Using asynchronous communication
- Applying more hooks
You can find the code on GitHub.
Step 4: Integrate Open Weather API for Search
To get real weather data we will need to talk to a service. For this tutorial we’ll use the Open Weather service. The service is free but you will need to register and create a key to use the service and authenticate all API requests.
Creating a Service Interface Layer
To avoid cluttering components we will create a service interface layer to talk to the API. This could be a class or simply functions. Let’s use functions.
To create our service we will create a
WeatherService.ts file. To add some structure to help organise our project let’s create some folders:
components:contain all our components
services:contain all our services
model:contain our model files
If our application grew we would create feature folders and optionally use the folder pattern above within those.
I’m not going to go into the API in detail but the format will be similar to using other services, like making asynchronous
fetch requests against URLs. The APIs we’ll use are:
All of these are simple GET requests with query parameters to specify city id and search term. The query parameters must also provide the
appid you generated when registering for the free service. For example:
To avoid commiting the
appid in code we can read this from an environment variable at build time. This is again supported by
react-scripts employing special Webpack plugins. The environment variable must begin with
REACT_APP_ and can be read in from
process.env. This is normally a runtime call, but in this system, it will be replaced by the current value at build time.
With this initialization code in place, we can now easily build URLs for the requests e.g.
Defining the Model
Since we are in TypeScript we will want to strongly type the results coming back from the API. We can model the entire object or only the parts that we want to use. Let’s define a subset of the information coming back from the API in a new file
Defining the Search Service Endpoint
We will need a function to search for locations by string so in
WeatherService.ts add the following function:
If the search doesn’t find any results we will get a
404 status code so the function returns either
undefined or a
WeatherLocation object which will contain the city id. This code is written using async-await which simplifies working with promises (which
Bringing it All Together: Search
Now that we have our model and service layer, we can start to integrate this into our components. First, we can add the search. When an
onSearch event fires, instead of adding the string to an array we must:
- Call our
- Show an error if is nothing found or warning if it is already present
- This will require a new state
- Add the location to the
locationsarray if found
- So the type of the array must change
Let’s change the type of the array and add a state for an error and a warning.
The error and warning can then be integrated into the view:
We can see that the two blocks are almost identical so this is a perfect opportunity to break these out as components. I’ll leave this to the reader, or check out the final version to see a higher-order functional solution.
Next, let’s change the
addLocation handler to perform a search, resetting the error and warning beforehand.
The final step is to adjust the
LocationTable to use
WeatherLocation objects instead of strings.
If everything has worked, the app should now be able to search for locations and show errors.
We could, of course, go further and disable controls and show spinners while working.
Step 5: Showing the Current Weather
Adding a Current Location
We need to have some state at the top level to represent the current location. This should be highlighted in the table and the user should be able to select it from the table of locations.
This means we’ll need to have the current location state in
App and pass this down into the table. The table should also notify
App via a callback if the selected row changes.
Then in the
LocationTable component we must:
- Add these new props
- Destructure them in the components parameters
- Wire up highlighting formatting based on the
- Wire up
clickhandlers on the rows to fire an
onSelectcallback with the correct location.
Now we have a table where we can select the current location.
Extending the Model and Service
Showing the current weather will involve similar steps as search:
- Extend model for new Weather objects
- Add a new service function to get the weather for a location
Once again we’ll use a simplified model of what Open Weather is providing. We could reshape the data into nicer objects but we’ll consume the data as is and simply only define/type the bits we’re using.
Next, we’ll add a function to read the current weather at a specified location.
Finally, we can make a helper function to generate icon URLs.
Creating a Single Weather Entry Component
Now let’s create a component to render information about a weather object which will be passed in via props. This is using a little bit of foresight as we will instantiate this many times for our forecast.
components/WeatherEntry.tsx file and add the following code:
We’re simply choosing some of our properties and laying them out as we would with HTML. To display the timestamp we convert from the Unix number to a Date object. We could move the
convertUnixTimeToDate function out to a helpful utility file.
Creating a Weather Summary Component
Next, let’s create a
components/WeatherSummary.tsx component that will be given a possibly null location; it will read the weather information about that location and display it using the previous
So this component is going to have to do some asynchronous work. It will render before it has the data it needs and when the asynchronous work completes, the data will be present. To do asynchronous work we need to utilize the
A simplified form of this hook is:
action is a function that will perform some side effects of the render. Typically this will eventually update some piece of state. The dependencies parameter controls when the action is re-executed. Realize that the
useEffect line is executed on every component render (as it’s really just a normal function call) but it will not necessarily call the action on every render. The dependency parameter controls when it chooses to call the action. In this variant, we will pass in an array of data that will cause the action to be re-executed if the data changes between renders.
These dependencies are any data that the action uses. So in our case, the action is reading the weather for a location so the dependency array contains the location.
Notice how, when the
readWeather completes, we set the
weather state. Also, note that we’re not using async/await—this is due to the way
useEffect expects an action that either returns a cleanup function or returns nothing. All async functions return Promises so they can’t be used directly for the action parameter.
The rest of the component renders based on the state of data:
Returning null simply causes the component not to render while the location or the weather are null. Note how the rendering section of the component is always synchronous: it renders based upon the current values of the state and props. Separate from this is the side effects that affect the render indirectly by setting state which triggers a rerender with now updated values.
Finally, we can use this at the top level in
Step 6: Adding a Forecast
For our final step, we can reuse our
WeatherEntry component to show a list of weather forecasts.
Extending the Service
We need a new function in the service layer to read the forecast. This is similar to
readWeather but we’re returning 8 forecasts at 3-hour intervals to give us a 24-hour forecast. The data returned has an inner
list property which is what we return.
Extending the Summary
Now we can extend the summary component to read in the forecast in the same effect as the read weather. We can use a
Promise.all call to execute the two requests at the same time. We’ll also use an inner function so that we can use async-await without making the
useEffect action itself async.
Now that we’ve defined our state and populated it, we can build up the view.
Note that the
null check is doing more than simply controlling visibility.
forecast are all nullable, which means TypeScript will not let us simply use them. For example,
forecast.map would fail if
forecast was null. But in this
if check we return if they are null so in any code that follows TypeScript understands they cannot be null so the type automatically changes without a cast/type assertion.
forecast changes from
Weather | null to simply
We have our forecast but it doesn’t look great as a vertical list. We should now add some basic styling. Add a
components/WeatherSummary.scss file with the following content:
To support SCSS we need to add the
node-sass package to our project and restart the development server. I’m using version 4.14 as there were incompatible packages with version 5.
npm install --save firstname.lastname@example.org
We can now import this within
It’s important to understand that, although we can add any number of CSS (or other) style files in this way, any styles we define will be global. Even if they are imported within individual components. Contrast this with something like Angular which encapsulates styles per component by default.
Another option for styling is to add some inline styles using objects. The naming is camel-case which differs from pure CSS.
There are other options such as CSS modules or
I hope you enjoyed that. If you’ve followed along you’ve gained a good introduction to using React to build single-page applications.