When I render my flatlist, it seems to duplicate items inside it (feedCache has one index and it will render the data for this index twice). Here's the code for the flatlist:
const FeedBody = React.memo(() => {
return (
<FlatList
data={feedCache}
renderItem={({ item }) => {
return (
<FeedPost
item={item}
/>
)
}}
keyExtractor={item => item.id}
/>
)
})
return (
<>
{feedLoaded && feedCache && feedReturnCache
? <FeedBody />
: <AppLoading />
}
</>
)
At the top of the document, in the useEffect, I fetch data from an API and write parts to feedCache and feedReturnCache. Once this completes feedLoaded is set to true and the feed body is supposedly rendered. Despite this, I'm convinced the FeedBody component is still re-rendering due to state updates. This causes duplication of items inside the flatlist. Is there a way to fix/prevent this?
Any help would be appreciated, thanks.
(useEffect code)
const [feedLoaded, setFeedLoaded] = useState(false)
const [feedCache, setFeedCache] = useState(null)
const [feedReturnCache, setFeedReturnCache] = useState(null)
useEffect(() => {
feedMounted = true
server("POST", "/content/feed", {
token: user.token,
cachePresent: false,
metric: "new"
}, (data, http, error) => {
if (!error) {
const toBeStatefulFeedReturnCache = new Array()
for (let i = 0; i < data.length; i++) {
toBeStatefulFeedReturnCache.push({
id: data[i].id,
read: false
})
if (i + 1 === data.length) {
if (feedMounted) {
setFeedCache(data)
setFeedReturnCache(toBeStatefulFeedReturnCache)
setFeedLoaded(true)
}
}
}
} else {
throw error
}
})
return () => {
feedMounted = false
}
}, [])
Try to fix duplication in array with set