📜 ⬆️ ⬇️

Guide React Native - create an application for iOS. Part 1.2, 1.3

→ Transfer from here
→ Continued. Start here

2. Extracting data from the API


In this section, we will connect to the Unsplash.it site API and request wallpaper information. But before we get down to the interesting, we need to do something.

Declaring classes in ES2015 style


In the index.ios.js file you see the existing code. He is responsible for outputting content to the emulator.
')
image

In the index.ios.js file , we see the line var SplashWalls = React.createClass({ ... }) . We will change it. In this tutorial, we will use the ES2015 syntax to declare classes.
We, the developers, are curious. You may want to ask: “Why? Why use classes from ES2015? ".

Everything is explained by personal preferences. I programmed a lot in OOP languages ​​and the class is closer to me than function . In addition, using class we can write cleaner code, because we do not need to add (;) after declaring each method.

On the other hand, we lose some of the “chips”, such as binding or access to the isMounted () method, although this is not so important, because you don’t lose very little without using them.

The class can be created in any way. I recommend the class . This is a new feature and sooner or later you will have to use ES2015. Using this manual, you have to use the syntax of ES2015, you simply have no choice!

Read more about this in the article “React.Component vs React.createClass” by Naman Goel and Zach Silveira.

After making changes, the code should look like this:

 class SplashWalls extends Component{ render() { return ( . <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> .</View> ); } }; 

For people unfamiliar with React, the code contained in braces may seem a bit strange. But this is the usual XML-shaped syntax, which is called JSX. Read more here .

Hey! And what is this Component, a copy of which we create? And this is the right question. If we run the project now, we get an error that says that the Component is not declared. You can fix this in two ways: replace the Component with a React.Component or import the Component, as shown below.

In this and the following code examples, I will wrap up new pieces of code in /***/ to make it easier for you to track changes. If you copy the code from here, make sure that you do not copy /***/ along with the code. JSX does not support comments of the form /*...*/ , therefore, inserting such comments, you cannot launch the application.

 'use strict'; var { AppRegistry, StyleSheet, Tex .t, View, /***/ Component /***/ } = React; 

The code above saves you from having to write extra code. If you don’t insert these lines of code, you’ll have to write React.AppRegistry instead of AppRegistry. Not bad, right? Return to Xcode and run the project again to make sure everything works.

The first thing we need to do is add a constructor to the SplashWalls class. In the constructor, we initialize the state variables (state). At the moment we need two variables:


Add a constructor to the code as shown below:

 class SplashWalls extends Component{ /***/ constructor(props) { super(props); this.state = { wallsJSON: [], isLoading: true }; } /***/ ... } 

Now we will create a fetchWallsJSON method that will receive json data. Back off a few lines from the constructor's closing brackets and add the following:

 fetchWallsJSON() { console.log('Wallpapers will be fetched'); } 

We want this function to start as soon as our component is successfully mounted. Add the componentDidMount() method. Most of the methods will be added to the SplashWalls class. I will mention separately if the methods will be added to another place.

componentDidMount() is a life-cycle method that starts immediately after the first rendering (rendering) of the React component.


Here you can read more about the life cycle methods of the React component. Since we are using the ES2015 syntax, we can omit the getInitialState method. It is replaced by declaring this.state in the constructor.

I like to separate the methods I create from the life cycle methods. You should follow the same rule.

Let's declare the componentDidMount() method:

 componentDidMount() { this.fetchWallsJSON(); } 

Notice that in the fetchWallsJSON() method, we fetchWallsJSON() message to the console. And where is the console itself? Let's get a look.

Make sure the emulator window is in focus and click Cmd + Control + Z. From the pop-up menu, choose Debug in Chrome (debug in Chrome). A new tab will open. From the same tab, go to Developer Tools (Option + Cmd + J). In the console, you will see the message “Wallpapers will be fetched”.


Do not close the debugging window yet. Go to unsplash.it/list in a new tab. The tab area should be filled with a JSON array. Each element in it is a JS object containing data about a separate wallpaper file.

Let's make it so that the fetchWallsJSON () method does something more than just output the message to the console.

  fetchWallsJSON() { /***/ var url = 'http://unsplash.it/list'; fetch(url) .then( response => response.json() ) .then( jsonData => { console.log(jsonData); }) .catch( error => console.log('Fetch error ' + error) ); /***/ } 

Update the emulator (Cmd + R) or, better, enable live reload (live reload) by pressing Cmd + Ctrl + Z and selecting “Enable live reload”. By activating the live reboot, you will not need to update the emulator each time after changing the code. Just save the file in your IDE and the emulator will automatically update the drawing. If you previously developed applications in Xcode or Android Studio, you will really like this "trick", because you will not need to recompile the application each time (as they said at one RN conference, now you will not have time for a cup of tea (- “Render!”), As before - approx. Translator).

After some time, after making changes, you should see the following in the emulator:


Great, we were able to get JSON data from the API. If you noticed, there was some delay before the message appeared in the console. It is connected with the fact that the data was downloaded from the server, which takes some time.

It seems like a good time to add a screen showing the download.

Boot screen


By the end of this section, we will create a loading screen that will be displayed when JSON data is being loaded.

First, clear everything in the render() method of the SplashWall class and add the following lines of code:

 render() { var {isLoading} = this.state; if(isLoading) return this.renderLoadingMessage(); else return this.renderResults(); } 

We have indicated two new methods. Let's declare them:

  renderLoadingMessage() { return ( . <View style={styles.loadingContainer}> <ActivityIndicatorIOS animating={true} color={'#fff'} size={'small'} style={{margin: 15}} /> <Text style={{color: '#fff'}}>Contacting Unsplash</Text> .</View> ); } renderResults() { return ( . <View> <Text> Data loaded </Text> .</View> ); } 

Depending on the value of the isLoading variable, two components of the View will be drawn. If isLoading is true, we will display a loading indicator and the text “Contacting Unsplash” (“Connecting with Unsplash”). Otherwise, we will display the data, instead of which at the moment we will have the text "Data loaded" displayed.

However, we forgot something: we do not change the value of the isLoading variable after loading the data. Let's do that. Let's go back to the fetchWallsJSON method and add something:

 fetchWallsJSON() { var url = 'http://unsplash.it/list'; fetch(url) .then( response => response.json() ) .then( jsonData => { console.log(jsonData); /***/ this.setState({isLoading: false}); //update isLoading /***/ }) .catch( error => console.log('Fetch error ' + error) ); } 

setState is one of the React's Component API methods. This is the main method used to run a user interface update.

Notice in the renderLoadingMessage method renderLoadingMessage we are using the new ActivityIndicatorIOS component (load indicator). We need to import it so that we can use it:

 'use strict'; var { AppRegistry, StyleSheet, Tex .t, View, Component, /***/ ActivityIndicatorIOS // Add new component /***/ } = React; 

We need to do one more thing before we can enjoy the result. If you notice, the View component, which contains the loading indicator, ActivityIndicatorIOS, has the styles.loadingContainer. We need to set this style. We need to find a piece of code starting with the words var styles = StyleSheet.create({…. In this code block we can see the styles that are already set. They refer to the default message “Welcome to React Native.” Delete all styles and set The styles for loadingContainer are as below:

 var styles = StyleSheet.create({ /***/ loadingContainer: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#000' } /***/ }); 

All styles that apply to components in RN are set in the same way. StyleSheet.create accepts a JS object containing styles. After that, you can access the style with the dot operator [.]. Also, as we applied the style to View:

 <View style={styles.loadingContainer}/> 

Styles can also be set in the line:

 <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#000' }} /> 

This unnecessarily clutters the code. Therefore, styles are best stored in a variable.

Styles are very similar to CSS, aren't they? This makes RN even easier for web developers. When you work in IDE (Xcode, for example), you have a StoryBoard, which allows you to directly drag and drop UI elements on the screen, such as buttons. In RN, this cannot be done, but it is not so bad after all.

React Native uses flexbox to position elements on the screen . Having mastered the flexbox, you will not be difficult to position the elements. This is one of those things that you should try to understand the difference.

Save the changes, go to the emulator and press Cmd + R. You should see the loading screen and then the screen that says “Data loaded”:



In the next section, we will add wallpaper filtering.

Source: https://habr.com/ru/post/328834/


All Articles