简体   繁体   中英

Re render React Native Flatlist on data fetch from API

I am working on a React Native app where i'm using Flatlist .I have a list to render.But i want to add items to the list which i'm getting from the API on button click. I can see my API data on the console but they are not rendering for some reason. Also the list page i'm talking about is a child component. Here's what it looks like:

 class ProductList extends Component { state = { isSpinner: false, newArr: [] }; onScrollEndDrag = async() => { this.setState({ isSpinner: true }); return await fetch( `myAPI` ).then(response => response.json()).then(json => { this.setState({ newArr: [...this.state.newArr, ...(json || [])] }) return json; }).catch(error => console.log(error)); } this.setState({ isSpinner: false }); } render(){ const list = [data1,data2,data3]; return( <Fragment> <FlatList key={this.key} data={[...list,...this.state.newArr]} renderItem={this.renderItem} /> <Button title='Load More' onPress={this.onScrollEndDrag}> </Button> </Fragment> ) } }

What can be done to show the new API data with the existing list?

Since you are anyways using async await no need of again using .then and .catch instead you can do it the below way.

onScrollEndDrag = async() => {
    this.setState({ isSpinner: true });
    try {   
        const response = await fetch(`myAPI`);
        const json = await response.json();
        this.setState({ 
          newArr: [...this.state.newArr, ...(json || [])], 
          isSpinner: false 
        }) 
    } catch(error) { 
        console.log(error);
        this.setState({ isSpinner: false });
    }

} 

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM