Make professional mobile apps with React Native and Typescript — Fetch APIs (Chapter 3 — Part 4)

Thinh Tran
5 min readApr 20, 2020

Fetch data from server with React Native.

Photo by Adeolu Eletu on Unsplash

Except for some applications such as offline games, utility tools which don't need data from servers, most of the mobile applications interact and transfer data between them and backend servers. In this part, we'll learn how to do it to make our weather forecast tool.

Let’s continue from the previous part. Otherwise, clone the repository.

git clone -b integrate_3rd_components https://github.com/thinhtran3588/react-native-starter-kit.git

The first step is to set up the API. In this tutorial, we use Openweathermap to get weather data. The first step is to go to their website, register a new free account and confirm it by email. After that go to https://home.openweathermap.org/api_keys to retrieve your API key.

And put it in a configuration file. Create a new folder src/core/config and add a new file: index.ts. We store out API key in that file and other configurations.

config/index.ts

Pro tip: It's used for learning so we store the API key directly in our code. However, for a production application, due to security reasons, in this case we should store it in our backend system and expose our own APIs as a proxy to call OpenWeatherMap APIs then call our APIs from our app.

Pro tip: It's a best practice to store all configuration data in a central place so that we can manage and modify them if needed easily. Store it in a ts/json makes IntelliSense available so it's can be referenced automatically from the code.

We'll need to work with the Date type so let's install dayjs (2KB immutable date library alternative to Moment.js with the same modern API)

yarn add dayjs

Now, we'll make a helper function to format Date values. Create a new folder src/core/helpers. Then add 2 new files format_date.ts & index.ts

format_date

Note that in the formatDate function, we use dateFormat from config to format the date. The input value is a Unix timestamp value.

Prop tip: store common functions in helpers so they can be reused in the project.

Now we'll add a new weather service to retrieve data from OpenWeatherMap. Create a new folder src/modules/weather/services and add 2 new files weather_service.ts & index.ts.

weather services

Pro tip: we can set default values to parameters as we do to parameters unit & lang.

Pro tip: if the number of parameters is less than 3, we can define the function as const func = funcA(para1: string, para2: string) . If not, we should only define 1 object parameter and pass all data as a JSON object const func = funcA(para: {para1: string; para2: string}) . It makes updating easier in the future without worrrying about their orders.

Pro tip: put the logic of retrieving data and formatting it in a separate service make the component cleaner and a preferable way to separate the logic. The result can be reconstructed and formatted into a new model to best fit our app, not always the same structure as the API result.

Pro tip: React Native uses the same Fetch API as the browser. You can learn more about it here.

Then add missing interfaces. Create a new folder src/modules/weather/interfaces and add weather_data.ts, weather_service.ts & index.ts.

interfaces

The preparation is done. It's time to show it on the screen. Go to src/modules/weather/screens/weather_screen and create new files with the below structure.

weather_screen
components
weather_item
weather_item.tsx
index.ts
weather_screen.tsx
weather_screen.styles.ts
weather screen

Update src/core/components/index.ts

components/index.ts

Reload your app. It should look like the below screenshots. You can try press Toggle unit and the unit changes from Celsius(°C) to Fahrenheit(°C) and vice versa.

weather screenshots

Now let look into the code. The WeatherScreen component has a child component called WeatherItem used to display weather in each day.

Pro tip: Break a big screen into smaller components.

The WeatherScreen component has a useEffect hook. It's triggered when the screen is rendered and call the weatherService.getDailyWeatherForecast to get weather data. After that, it updates the weatherForecasts state and the screen is re-rendered again with updated data. When processing the API call, the screen displays No data for a very short time. When you press the Toggle unit button, the conditions state is updated with a new unit. Because it's a dependency of the useEffect hook, the function inside the hook is triggered again and the screen is updated with new data (new unit) from API.

That's a typical flow when working with backend API.

Now you've already made it work right. It's time to make it look nice.

Look at the toggleUnit function. When updating a state which is a JSON object, we often use spread syntax to update it by return a new object with updated values. Note that the state is immutable and we must not update it directly. However, if we store the state as a big (and nested) JSON object (which we shouldn't do at all), the update syntax becomes very verbose. Let's make it easy with immer, a small but powerful library to update states. We'll use the hook version. Install it first.

yarn add immer use-immer

Add import {useImmer} from ‘use-immer’; to weather_screen.tsx and update the toggleUnit function

const toggleUnit = (): void => {   setConditions((draft) => {      draft.unit =         conditions.unit === config.weather.unitCodes.celsius         ? config.weather.unitCodes.fahrenheit         : config.weather.unitCodes.celsius;   });};

It should work as before but the code is much cleaner.

Pro tip: if the state is a primitive value, use useState. Otherwise, use useImmer.

Now we'll add 2 new components: react-native-snap-carouse (a beautiful slider component) & react-native-fast-image (a performant image component). Run

yarn add react-native-snap-carousel
yarn add --dev @types/react-native-snap-carousel
yarn add react-native-fast-image

Go to src/modules/weather/screens/weather_screen and update weather_screen.tsx, weather_screen.styles.ts, weather_item.tsx, weather_item.styles.ts.

update components.

Update core/components/index.ts & core/helpers/format_date.ts

core/components/index.ts & core/helpers/format_date.ts

Run yarn android & yarn ios to rebuild your app since there are new binary libraries. You should have a beautiful weather forecast screen now.

final result

Congratulations! That’s all we need to do in this part.

You can clone the sample here:

git clone -b fetch_api https://github.com/thinhtran3588/react-native-starter-kit.git

Things you have learned in this part:

  1. use Fetch API to interact with backend API.
  2. use the useImmer hook for JSON states.
  3. use react-native-snap-carouse & react-native-fast-image

--

--

Thinh Tran

Software developer. Interested in web/mobile application development with React, React Native, Typescript, Nodejs and AWS.