Bird
Raised Fist0
React Nativemobile~20 mins

Axios library in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: User List
This screen fetches and shows a list of users from a remote API using Axios. It displays user names in a scrollable list.
Target UI
-------------------------
|       User List       |
-------------------------
| • Loading...          |
|                       |
|                       |
|                       |
|                       |
-------------------------
Use Axios to fetch user data from https://jsonplaceholder.typicode.com/users
Show a loading text while fetching data
Display the user names in a scrollable list after data loads
Handle errors by showing an error message
Starter Code
React Native
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import axios from 'axios';

export default function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // TODO: Fetch user data with Axios here
  }, []);

  return (
    <View style={styles.container}>
      {/* TODO: Show loading, error or user list here */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff'
  },
  item: {
    fontSize: 18,
    paddingVertical: 10
  },
  error: {
    color: 'red',
    fontSize: 16
  }
});
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
React Native
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import axios from 'axios';

export default function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        setUsers(response.data);
        setLoading(false);
      })
      .catch(() => {
        setError('Failed to load users');
        setLoading(false);
      });
  }, []);

  if (loading) {
    return (
      <View style={styles.container}>
        <Text>Loading...</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.container}>
        <Text style={styles.error}>{error}</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={users}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => <Text style={styles.item}>{item.name}</Text>}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff'
  },
  item: {
    fontSize: 18,
    paddingVertical: 10
  },
  error: {
    color: 'red',
    fontSize: 16
  }
});

This solution uses the Axios library to fetch user data from a public API when the component loads.

We use useEffect to run the fetch once after the screen appears.

While loading, it shows a simple 'Loading...' text.

If there is an error fetching data, it shows a red error message.

When data is loaded successfully, it displays the user names in a scrollable list using FlatList.

This approach keeps the UI responsive and handles errors gracefully.

Final Result
Completed Screen
-------------------------
|       User List       |
-------------------------
| Leanne Graham         |
| Ervin Howell          |
| Clementine Bauch      |
| Patricia Lebsack      |
| Chelsey Dietrich      |
| Mrs. Dennis Schulist  |
| Kurtis Weissnat       |
| Nicholas Runolfsdottir|
| Glenna Reichert       |
| Clementina DuBuque    |
-------------------------
When the screen loads, it shows 'Loading...' text.
After data loads, the list of user names appears.
If the fetch fails, an error message 'Failed to load users' is shown.
Stretch Goal
Add a pull-to-refresh feature to reload the user list when the user swipes down.
💡 Hint
Use FlatList's refreshing and onRefresh props to implement pull-to-refresh.

Practice

(1/5)
1. What is the main purpose of using the Axios library in a React Native app?
easy
A. To make HTTP requests to fetch or send data
B. To style components with CSS
C. To manage app navigation between screens
D. To store data locally on the device

Solution

  1. Step 1: Understand Axios functionality

    Axios is a library designed to simplify making HTTP requests like GET and POST.
  2. Step 2: Identify Axios use in React Native

    It helps fetch data from servers or send data to them, which is essential for dynamic apps.
  3. Final Answer:

    To make HTTP requests to fetch or send data -> Option A
  4. Quick Check:

    Axios = HTTP requests [OK]
Hint: Axios is for internet requests, not styling or navigation [OK]
Common Mistakes:
  • Confusing Axios with styling libraries
  • Thinking Axios manages navigation
  • Assuming Axios stores data locally
2. Which of the following is the correct syntax to make a GET request using Axios in React Native?
easy
A. axios.fetch('https://api.example.com/data')
B. axios.get('https://api.example.com/data')
C. axios.post('https://api.example.com/data')
D. axios.request('https://api.example.com/data')

Solution

  1. Step 1: Recall Axios GET method

    The correct method to fetch data is axios.get(url).
  2. Step 2: Check other options

    axios.fetch is not a valid Axios method, axios.post sends data, and axios.request is more generic but requires config.
  3. Final Answer:

    axios.get('https://api.example.com/data') -> Option B
  4. Quick Check:

    GET request = axios.get() [OK]
Hint: Use axios.get() for fetching data [OK]
Common Mistakes:
  • Using axios.fetch which does not exist
  • Confusing get with post method
  • Using axios.request without config object
3. What will be logged to the console after this Axios GET request succeeds?
axios.get('https://api.example.com/user')
  .then(response => console.log(response.data.name))
  .catch(error => console.log('Error'));
Assuming the server responds with { "name": "Alice" }.
medium
A. response
B. Error
C. Alice
D. undefined

Solution

  1. Step 1: Understand Axios response structure

    Axios returns a response object where the actual data is inside response.data.
  2. Step 2: Access the name property

    The code logs response.data.name, which is "Alice" from the server response.
  3. Final Answer:

    Alice -> Option C
  4. Quick Check:

    response.data.name = Alice [OK]
Hint: Access data via response.data in Axios [OK]
Common Mistakes:
  • Logging response instead of response.data
  • Expecting data directly without .data
  • Not handling promise with then/catch
4. Identify the error in this Axios POST request code snippet:
axios.post('https://api.example.com/login',
  { username: 'user1', password: 'pass123' }
).then(response => {
  console.log('Login successful');
}).catch(error => {
  console.log('Login failed');
});
medium
A. No error, code is correct
B. Missing await keyword for async call
C. Incorrect URL format
D. POST data should be a string, not an object

Solution

  1. Step 1: Review Axios POST syntax

    Axios.post takes URL and data object as parameters, which is correct here.
  2. Step 2: Check for syntax or usage errors

    The code uses promise chaining with then/catch correctly; await is optional.
  3. Final Answer:

    No error, code is correct -> Option A
  4. Quick Check:

    Axios.post with object data is valid [OK]
Hint: Axios.post accepts object data without await [OK]
Common Mistakes:
  • Thinking await is mandatory with then/catch
  • Assuming data must be JSON stringified manually
  • Confusing URL format with error
5. You want to fetch user data and show a loading message while waiting. Which code snippet correctly uses Axios with React Native hooks to handle loading and errors?
hard
A. const [loading, setLoading] = useState(false); useEffect(() => { axios.get('/user') .then(() => setLoading(false)) .catch(() => setLoading(false)); }, []);
B. const [loading, setLoading] = useState(false); useEffect(() => { axios.get('/user') .then(() => setLoading(true)) .catch(() => setLoading(false)); }, []);
C. const [loading, setLoading] = useState(true); useEffect(() => { setLoading(false); axios.get('/user') .then(() => setLoading(true)) .catch(() => setLoading(false)); }, []);
D. const [loading, setLoading] = useState(false); useEffect(() => { setLoading(true); axios.get('/user') .then(() => setLoading(false)) .catch(() => setLoading(false)); }, []);

Solution

  1. Step 1: Initialize loading state correctly

    Loading should start as false, then set to true when request starts.
  2. Step 2: Set loading true before Axios call and false after response or error

    This ensures UI shows loading while waiting and hides it after.
  3. Final Answer:

    Initialize loading false, set true before request, false after -> Option D
  4. Quick Check:

    Loading true during request = const [loading, setLoading] = useState(false); useEffect(() => { setLoading(true); axios.get('/user') .then(() => setLoading(false)) .catch(() => setLoading(false)); }, []); [OK]
Hint: Set loading true before request, false after response [OK]
Common Mistakes:
  • Starting loading as true but not setting it properly
  • Setting loading true after request finishes
  • Not handling loading state at all
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard