Home > Software design >  How to go back to previous scroll place when navigation to go back?
How to go back to previous scroll place when navigation to go back?

Time:11-22

I got a productList page and product details page

In the product list page I got a scroll handler on the flatList which load more data when the end of the list is reached.

The product list component is something like this

let productList = useSelector(state => state.productReducer.productList);

const [numbersOfItem, setNumberOfItem] = useState(20);
const [itemList, setItemList] = useState(productList);


const handleLoadMoreData = async () => {
        setLoadingMoreData(true);
        try {
            let requestNumber = numbersOfItem   20;
            setNumberOfItem(requestNumber);
            await dispatch(
                fetchProductList(
                    categoryTitle,
                    subCategoryName,
                    activeTab,
                    requestNumber,
                ),
            );
        } catch {
            console.log('error');
        } finally {
            setLoadingMoreData(false);
        }
    };

<FlatList
    data={itemList}
    numColumns={2}
    nestedScrollEnabled
    columnWrapperStyle={styles.flatItemColumn}
    scrollEnabled
    scrollEventThrottle={16}
    snapToAlignment="start"
    decelerationRate={'fast'}
    showsHorizontalScrollIndicator={false}
    renderItem={renderIndividualItem}
    keyExtractor={(item, index) => String(index)}
    onEndReached={() => handleLoadMoreData()}
/>

After Scrolling for a while when I see a product I wanna explore I will goes into the product details page

Inside the product details page when I click navigation.goBack(). The scroll position in the productList is go back to the place of 20th item. I think its because the default display is setNumberOfItem is set to 20.

How can I change this behavior.

CodePudding user response:

Adding an Api Call in a focus callBack in the screen that you want to go back to, can help solve this problem.(ProductList)

   React.useEffect(() => {
          fetchData();//func to get the data
          const willFocusSubscription = props.navigation.addListener('focus', () => {
            fetchData();//call it here as well
        });

        return willFocusSubscription;
    }, []);

CodePudding user response:

Use theinitialScrollIndex prop of the FlatList component to order the index where you want to start the FlatList. And find out how to know from which screen you come from when your productList page get focused

  • Related