I have an item page on which I render a flatlist of comments related to the item, the problem that I have is when I change item, the api call with the new props(itemId) doesn't happen and the comments from the previous item are rendered.
I'm certain that the new itemId is being passed to the screen since everything else changes (name, image, description...)
The way you reach the item page is through the shop page rendering a list of pictures of items (where I pass all the props needed to render the item on the item page)
I do notice that when I'm on item page and then press back to go back to shop page and then click on another item, the item page shows the data of the previous item for half a second before updating, but the list just never updates it keeps making the call with the old itemId. I use fetch to get the list, I've tried with axios as well, same result.
componentDidMount() {
this._isMounted = true;
const { navigation } = this.props;
this.focusListener = navigation.addListener('didFocus', async () => {
await fetch("https://api..." + navigation.getParam('itemId'))
.then(response => response.json())
.then((responseJson) => {
this.setState({
loading: false,
dataSource: responseJson
})
console.log("response Comments:" + JSON.stringify(responseJson));
console.log('the state of item id -->', this.props.navigation.getParam('itemId'))
});
}
}
when I console.log, I get the right itemId but it seems like the call happens before it receives the new props...
I'm relatively new to React Native and coding in general so please let me know if I need to be more clear.
Thanks for your help!
I faced the similar issue. It was because the props
of FlatList
was remaining the same. Although for individual renderItem
, it was changing but FlatList
component was unaware of that.
To solve this, you can use the extraData prop.
So, if you set extraData
prop to FlatList
like extraData={this.props}
, this will force reloading list when any of the prop of parent component changes.