Tanmoy Sarker
Tanmoy Sarker

Reputation: 1266

Adding object arrays from diffrerent api responses

I'm working on a React Native app where i'm using FlatList. The data i'm showing in the FlatList are coming from API response. Now, the API throws different data each time on a button click. I want to add all the responses after button press and show in the FlatList. I have done till this part here:

state = {
count: 1,
newArr: []
};

onScrollEndDrag = async () => {
this.setState({ count: this.state.count + 1 })
return await fetch(
    `$myAPI/products/` + `?page=${this.state.count}`
)
    .then(response => response.json())
    .then(json => {
        this.setState({ newArr: json })
        return json;
    })
    .catch(error => warn(error));
}

render(){
const list = [data1, data2, data3]
return (
    <Fragment>
        <FlatList
            key={this.key}
            data={[...list, ...this.state.newArr]}
            renderItem={this.renderItem}
            scrollEventThrottle={1}
        />

        <Button title='Load More' onPress={this.onScrollEndDrag}></Button>
    </Fragment>
)
}

It shows the list. But doesn't show the added newArr. How this can be done that on pressing Load newer response will be added to the previous one.

Upvotes: 0

Views: 39

Answers (2)

Siraj Alam
Siraj Alam

Reputation: 10025

I think the problem is in this line

this.setState({ newArr: json })

You're replacing the previous data with the newer one. Change it to merge with the previous data.

this.setState({ newArr: [...this.state.newArr, ...(json || [])] })

Upvotes: 1

Nikhil Asrani
Nikhil Asrani

Reputation: 111

The issue here is that your data keeps getting reset/changed everytime your render function is called. why don't you keep newArr as your source of truth for your data? Try the following:

state = {
count: 1,
newArr: [data1, data2, data3]
};

onScrollEndDrag = async () => {
this.setState({ count: this.state.count + 1 })
return await fetch(
    `$myAPI/products/` + `?page=${this.state.count}`
)
    .then(response => response.json())
    .then(json => {
        this.setState({ newArr: [...newArr, json] })
        return json;
    })
    .catch(error => warn(error));
}

render(){
return (
    <Fragment>
        <FlatList
            key={this.key}
            data={this.state.newArr}
            renderItem={this.renderItem}
            scrollEventThrottle={1}
        />

        <Button title='Load More' onPress={this.onScrollEndDrag}></Button>
    </Fragment>
)
}

Upvotes: 0

Related Questions