Skip to content

Commit

Permalink
Fix scrollTo called when not needed
Browse files Browse the repository at this point in the history
  • Loading branch information
janicduplessis committed Aug 1, 2024
1 parent c804881 commit 13c9acb
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/components/FlatList/index.android.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
import {useFocusEffect} from '@react-navigation/native';
import type {ForwardedRef} from 'react';
import React, {forwardRef, useCallback, useContext} from 'react';
import React, {forwardRef, useCallback, useRef} from 'react';
import type {FlatListProps, NativeScrollEvent, NativeSyntheticEvent} from 'react-native';
import {FlatList} from 'react-native';
import {ActionListContext} from '@pages/home/ReportScreenContext';

// FlatList wrapped with the freeze component will lose its scroll state when frozen (only for Android).
// CustomFlatList saves the offset and use it for scrollToOffset() when unfrozen.
function CustomFlatList<T>(props: FlatListProps<T>, ref: ForwardedRef<FlatList>) {
const {scrollPosition, setScrollPosition} = useContext(ActionListContext);
const lastScrollOffsetRef = useRef(0);

const onScreenFocus = useCallback(() => {
if (typeof ref === 'function') {
return;
}
if (!ref?.current || !scrollPosition?.offset) {
if (!ref?.current || !lastScrollOffsetRef.current) {
return;
}
if (ref.current && scrollPosition.offset) {
ref.current.scrollToOffset({offset: scrollPosition.offset, animated: false});
if (ref.current && lastScrollOffsetRef.current) {
ref.current.scrollToOffset({offset: lastScrollOffsetRef.current, animated: false});
}
}, [scrollPosition?.offset, ref]);
}, [ref]);

// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
const onMomentumScrollEnd = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => setScrollPosition({offset: event.nativeEvent.contentOffset.y}), []);
const onMomentumScrollEnd = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
lastScrollOffsetRef.current = event.nativeEvent.contentOffset.y;
}, []);

useFocusEffect(
useCallback(() => {
Expand Down

0 comments on commit 13c9acb

Please sign in to comment.