Repository navigation
How does initialScrollIndex work with async data?
#473
|
According to the docs: https://legendapp.com/open-source/list/v3/api/#initialscrollindex
Now I would expect that once the data has finished fetching, that the scroll adjusts automatically, but that didn't happen in my tests. Am I using it wrong? What is the alternative? Using |
Replies: 2 comments 1 reply
|
<LegendList data={[]} initialScrollIndex={someKnownIndex} />then later If So for your case, these are the practical options: // 1. Render the list only once data + index are known
if (!data || scrollIndex == null) return <Loading />;
return <LegendList data={data} initialScrollIndex={scrollIndex} />;or remount the list when the initial target becomes known: <LegendList
key={scrollIndex == null ? "loading" : `target-${scrollIndex}`}
data={data}
initialScrollIndex={scrollIndex ?? 0}
/>or use the ref after async data/index are ready: useEffect(() => {
if (data.length && scrollIndex != null) {
listRef.current?.scrollToIndex({ index: scrollIndex, animated: false });
}
}, [data.length, scrollIndex]);If the target index is known before the data arrives, pass it up front. If the target can only be computed from the fetched data, the ref/effect approach is usually the clearest because it is no longer really an initial scroll target. |
|
@krotname was right, but that felt very messy to me. So in 3.0.7 I fixed it so that it will use the value of And also, doing a scrollToIndex in an effect will not work well. There's a very complex initial bootstrap window where items are still laying out and measuring, and adjusting positions to match the initial scroll, and a manual scroll in there will cause problems. So ideally you can just update to 3.0.7 and initialScrollIndex will work as expected, and you can remove the useEffect. |
@krotname was right, but that felt very messy to me. So in 3.0.7 I fixed it so that it will use the value of
initialScrollIndexat the time that data gets populated.And also, doing a scrollToIndex in an effect will not work well. There's a very complex initial bootstrap window where items are still laying out and measuring, and adjusting positions to match the initial scroll, and a manual scroll in there will cause problems.
So ideally you can just update to 3.0.7 and initialScrollIndex will work as expected, and you can remove the useEffect.