Day 3 of 5

Data Fetching and APIs

React Native uses the same fetch API as the browser. You will load data from a REST API, show a loading spinner, handle errors, and render a FlatList — the performant replacement for ScrollView when you have many rows.

jsx
import { useEffect, useState } from 'react';
import { FlatList, ActivityIndicator, Text, View, StyleSheet } from 'react-native';

export default function PostsScreen() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts?_limit=20')
      .then(r => r.json())
      .then(data => { setPosts(data); setLoading(false); })
      .catch(err => { setError(err.message); setLoading(false); });
  }, []);

  if (loading) return <ActivityIndicator size="large" style={{ flex:1 }} />;
  if (error) return <Text style={{ color:'red', padding:16 }}>{error}</Text>;

  return (
    <FlatList
      data={posts}
      keyExtractor={item => String(item.id)}
      renderItem={({ item }) => (
        <View style={styles.row}>
          <Text style={styles.title}>{item.title}</Text>
          <Text style={styles.body} numberOfLines={2}>{item.body}</Text>
        </View>
      )}
      ItemSeparatorComponent={() => <View style={{ height:1, background:'#eee' }} />}
    />
  );
}

const styles = StyleSheet.create({
  row: { padding:16, backgroundColor:'#fff' },
  title: { fontWeight:'700', marginBottom:4 },
  body: { color:'#555' },
});
Tip: FlatList only renders items visible on screen — much faster than ScrollView for long lists.

Exercise: Build a News Feed

  1. Fetch from https://hacker-news.firebaseio.com/v0/topstories.json
  2. Get the first 20 IDs then fetch each story
  3. Display title, score, and author in a FlatList
  4. Add pull-to-refresh with onRefresh/refreshing props
  5. Show an ActivityIndicator while loading

Day 3 Summary

Finished this lesson?