Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How to correctly set an array of fetched objects to a state in react and render the data in a FlatList

$
0
0

I can't seem to find a way to correctly type my Interfaces and Array of Objects to use in a FlatList.

I am using ReactNative with Typescript.

The json file I fetched was from the NewsAPI which provides JSON data like this.

{"status": "ok","totalResults": 10,    -"articles": [        -{            -"source": {"id": null,"name": "somename"        },"author": "someauthor","title": "sometitle","description": "somedesc","url": "someurl","urlToImage": "someimage","publishedAt": "somedate",     },+{ … },    ]}

My current attempt looks like this but I can't wrap my head around the right method to use the keys for the renderItems and the keyExtractor of the FlatList.

interface IState {news: {    [key: string]: IArticles},loading: boolean}interface IArticles { //Since I don't actually want all the values of the object I left some out    title: string,    url: string,    urlToImage: string}export default class NewsField extends React.Component<{}, IState> {constructor(props: IProps) {    super(props);}state: IState = {    news: [],    loading: true}componentDidMount() {    this.fetchNews(); //This is where I set the state and fetch the data}render() {    return (<View><FlatList                data={this.state.news}                renderItem={({ item, index }) => {                    return (<View style={styles.containerList}><Text>{item.title}</Text></View>                    );                }}                keyExtractor={({ item, index }) => item.title.toString();}            /></View>    )}

Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>