I need to create an horizontal FlatList, maybe like instagram stories, and trigger the onEndReached function at some time to know when download more items from backend.
Asked
Active
Viewed 246 times
1 Answers
0
Here's how I've tried to solve, maybe will be useful for someone, write me if you think there's error of maybe you have a better solution:
where:
maxBeforeTrigger:
the number of list's cells to scroll every time before triggering onEndReached. (similar to onEndThreshold for vertical flatlists).
stepWidth:
cell dimension.
const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);
var stepIndicies = [];
const AnimatedHFlatList = forwardRef(
(
{
onScroll,
onEndReached,
maxBeforeTrigger = 2,
stepWidth = width,
...props
},
ref
) => {
const scrollX = useSharedValue(0);
const [endIndex, setEndIndex] = useState(1);
const _onScroll = useAnimatedScrollHandler(
({ contentOffset: { x } }) => {
scrollX.value = x;
onScroll && runOnJS(onScroll)(x);
const currentStepIndex = Math.max(
0,
Math.round(x / (maxBeforeTrigger * stepWidth))
);
if (
x <= stepWidth * maxBeforeTrigger * endIndex &&
endIndex == currentStepIndex &&
!stepIndicies.includes(currentStepIndex)
) {
stepIndicies.push(currentStepIndex);
runOnJS(setEndIndex)(endIndex + 1);
onEndReached && runOnJS(onEndReached)(currentStepIndex);
}
},
[endIndex]
);
return <AnimatedFlatList ref={ref} {...props} onScroll={_onScroll} />;
}
);
export default memo(AnimatedHFlatList);

PietroPutelli
- 482
- 4
- 20