React Native Axios Get request example

Initialize an example react native example

expo init axiosExample

Install axios

cd axiosExample
yarn add axios
cd ios
pod install
cd ..

Run the app in Android and ios simulator

yarn android
yarn ios

Create accountService.js for making a GET request via axios using async and await.

import axios from 'axios';

export default getGithubAccountData = async () => {
    let res = await axios.get("https://api.github.com/users/octocat");
    console.log("getGithubAccountData res.data: ", res.data);
    return res.data;
}

In the App.js, import getGithubAccountData from accountService.js, add a function showData() to call getGithubAccountData and update the state with accountData, and it will show up on the view when the state is updated.

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import getGithubAccountData from './accountService';

export default class App extends Component {
  constructor() {
    super();
    this.state = {accountData: 'loading...'}
  }

  componentDidMount() {
    console.log("componentDidMount");
    this.showData();
  }

  render() {
    console.log("render");
    return (
      
        Account Data
        {this.state.accountData}
      
    );
  }

  showData() {
    getGithubAccountData()
    .then(data => {
      this.setState({accountData: JSON.stringify(data)});
    })
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  header: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  data: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search