Refresh the List in ReactNative
2 min readNov 16, 2023
To achieve this in a React Native application, you’ll need to follow these steps:
- Create a JSON file (or use a mock server/API for testing purposes).
- Fetch the data from the JSON file.
- Display the data in a FlatList component.
- Implement a refresh mechanism using a RefreshControl with a 1-minute interval.
Here’s a simple example:
1. Create a JSON file (data.json):
// data.json
{
"items": [
{ "id": 1, "name": "Item 1" },
{ "id": 2, "name": "Item 2" },
{ "id": 3, "name": "Item 3" },
// Add more items as needed
]
}
2. Fetch data and display in FlatList:
import React, { useState, useEffect } from 'react';
import { View, FlatList, Text, RefreshControl, StyleSheet } from 'react-native';
const MyFlatListWithRefresh = () => {
const [data, setData] = useState([]);
const [refreshing, setRefreshing] = useState(false);
const fetchData = async () => {
try {
const response = await fetch('path/to/data.json'); // Adjust the path accordingly
const jsonData = await response.json();
setData(jsonData.items);
} catch (error) {
console.error('Error fetching data:', error);
}
};
useEffect(() => {
fetchData();
}, []);
const onRefresh = () => {
setRefreshing(true);
fetchData();
setTimeout(() => {
setRefreshing(false);
}, 1000); // Refresh indicator will be visible for at least 1 second
};
const renderItem = ({ item }) => (
<View style={styles.item}>
<Text>{item.name}</Text>
</View>
);
return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item) => item.id.toString()}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}
/>
);
};
const styles = StyleSheet.create({
item: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#ccc',
},
});
export default MyFlatListWithRefresh;
In this example:
- The
fetchData
function fetches data from the JSON file. - The
useEffect
hook ensures that data is fetched when the component mounts. - The FlatList component renders the data with each item displayed in a simple view.
- The RefreshControl is added to the FlatList to provide a pull-to-refresh functionality.
- The
onRefresh
the function sets a refreshing state, fetches new data, and then resets the refreshing state after a timeout to simulate a 1-minute interval.
Please note that setTimeout
the onRefresh
function is used to keep the refresh indicator visible for at least 1 second. You can adjust the timeout duration based on your specific requirements.