I’m working on a React Native app that fetches data from Airtable. The issue is that Airtable’s API returns a maximum of 100 records per request by default. I need to implement pagination so that when users scroll to the bottom of my FlatList, more records get loaded automatically.
I’ve tried using the offset parameter from Airtable’s response, but my current implementation loads all available records at once instead of loading them in smaller chunks as the user scrolls.
Here’s my current approach:
const API_TOKEN = "your_api_token";
const DATABASE_ID = "your_base_id";
const SHEET_NAME = "MainTable";
const VIEW_TYPE = "Default view";
const BATCH_SIZE = 15;
const database = new Airtable({ apiKey: API_TOKEN }).base(DATABASE_ID);
const Dashboard = () => {
const [dataList, setDataList] = useState([]);
const [loading, setLoading] = useState(false);
const [nextOffset, setNextOffset] = useState(null);
useEffect(() => {
fetchInitialData();
}, []);
async function fetchInitialData() {
setLoading(true);
await fetchMoreData();
}
async function fetchMoreData() {
setLoading(true);
const result = await database(SHEET_NAME)
.select({
view: VIEW_TYPE,
pageSize: BATCH_SIZE,
offset: nextOffset
})
.all();
const combinedData = [...dataList, ...result];
setDataList(combinedData);
if (result.offset) {
setNextOffset(result.offset);
} else {
setNextOffset(null);
}
setLoading(false);
}
function displayItem({ item }) {
return <ImageCard source={item.fields.image} />;
}
function showLoadingIndicator() {
return loading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
) : null;
}
function onScrollEnd() {
if (!loading && nextOffset) {
fetchMoreData();
}
}
return (
<View style={styles.mainContainer}>
<FlatList
data={dataList}
renderItem={displayItem}
numColumns={2}
keyExtractor={(record) => record.id}
ListFooterComponent={showLoadingIndicator}
onEndReached={onScrollEnd}
onEndReachedThreshold={0.1}
initialNumToRender={BATCH_SIZE}
/>
</View>
);
};
export default Dashboard;
The problem is that instead of loading records in batches when scrolling, everything loads at once. What am I missing in my pagination logic?