Beginning React Native with Hooks by Lim Greg

Beginning React Native with Hooks by Lim Greg

Author:Lim, Greg [Lim, Greg]
Language: eng
Format: epub
Published: 2020-06-24T16:00:00+00:00


axios.get("https://api.github.com/search/users?q=greg")

.then(res => {

console.log(res.data.items);

});

Note: If you are unfamiliar with promises, a promise allows us to make sense out of asynchronous behavior. Promises provide handlers with an asynchronous action's eventual success value. Initially, the promise is pending, and then it can either be fulfilled with a value or be rejected with an error reason. When either of these options happens, the associated handlers queued up by a promise's then method are called. This lets asynchronous methods return values like synchronous methods instead of immediately returning the final value. The asynchronous method returns a promise to supply the value at some point in the future.

In useEffect , we use the get() method of axios and give the url of our API endpoint. We have a search term provided by the user from an input which we will implement later. The return type of get() is a promise. We subscribe to this promise with then so that when an ajax call is completed, the response is fed to the Promise and then pushed to the component.

We then pass in our callback function res => console.log(res.data.items) . Note that we have to access data.items property to get the items array direct as that is the json structure of the GitHub response. So when our ajax call is completed, we print the list of items returned which is the GitHub users search results.

useEffect

Now, we come to an important question. What’s useEffect ? And why do we place our data request and retrieval code in it? As stated in reactjs.org, “If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount , componentDidUpdate , and componentWillUnmount combined.”

Or if you are not familiar with React class component lifecycle methods, useEffect is called after our component renders. For e.g. when our GitHub component first renders, we want to make the API data request. Thus, we place our data retrieval code in it. We will dwell more into useEffect , but for now, let’s see the results we get when we run our app.

Running our App

Before we run our app, remember that we have to import and call our GitHub component in App.js .

import React from 'react';

import { Container } from 'native-base';

import GitHub from './GitHub';

export default function App() {



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.