I have a JSON file where new news items are constantly stored and added, their number is constantly changing. I want to output only the last 3 elements from this JSON file to the FlatList. How to do it?
Here is my JSON receipt and my FlatList:
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
const getNewsMain = async () => {
try {
const response = await fetch(`https://cdn.ertil-gorod.ru/json/ertnews.json?nocache`);
const json = await response.json();
setData(json.ertnews);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
useEffect(() => {
getNewsMain();
}, []);
<FlatList
data={data}
initialNumToRender={5}
keyExtractor={({ id }, index) => id}
renderItem={ ( { item } ) => (
<TouchableOpacity
style={ styles.ert__news__item }
onPress={ ( ) => navigation.navigate( 'FullNews', item ) }>
<Image
style={ styles.ert__image__news }
source={ { uri: item.img } }
/>
<Text style={ styles.ert__title__news }>{ item.name }</Text>
<Text style={ styles.ert__anons__news }>{ item.anons }</Text>
</TouchableOpacity>
)} />
If data is an array you can use the Array.slice
<FlatList
data={data.slice(-3)}
initialNumToRender={5}
keyExtractor={({ id }, index) => id}
renderItem={ ( { item } ) => (
<TouchableOpacity
style={ styles.ert__news__item }
onPress={ ( ) => navigation.navigate( 'FullNews', item ) }>
<Image
style={ styles.ert__image__news }
source={ { uri: item.img } }
/>
<Text style={ styles.ert__title__news }>{ item.name }</Text>
<Text style={ styles.ert__anons__news }>{ item.anons }</Text>
</TouchableOpacity>
)}
/>