0

I have a flatlist and inside the onViewableItemsChangedRef I want to set the value of another ref inside the component like so:

const MyComponent= (): JSX.Element => {
    const currentId = useRef('');

    const onViewableItemsChangedRef = useRef(({ viewableItems }) => {
        // I want to set currentId in here
    });

    return (
        <FlatList
            // other props here like data, renderItem, etc.
            ref={ref}
            keyExtractor={(item) => item.id
            onViewableItemsChanged={onViewableItemsChangedRef.current}
        />
    );
};

But when I try to set currentId.current inside of onViewableItemsChangedRef, it's always undefined.

I tried switching the useRef to useCallback instead, but I would keep getting the error listed here React Native FlatList onViewableItemsChanged callback encounter error after state changed rerender

Is there another way of doing this?

pfinferno
  • 1,779
  • 3
  • 34
  • 62

1 Answers1

0

onViewableItemsChangedRef.current contains the first function definition which is bound to the first values, instead you can use useCallback calling a ref function like this:

    const onViewableItemsChangedRef = useRef()
    onViewableItemsChangedRef.current = ({ viewableItems }) => {
        // I want to set currentId in here
    });
    onViewableItemsChanged = useCallback((...args)=>onViewableItemsChangedRef.current(...args),[])
    // now use onViewableItemsChanged instead of onViewableItemsChangedRef.current

Of course, you can use the effective arguments instead of ...args

Ahmed Lazhar
  • 718
  • 4
  • 10
  • Hmm, could you show a complete example if you get the chance? I'm seeing this error: `Cannot redeclare block-scoped variable 'onViewableItemsChangedRef'.` on `const onViewableItemsChangedRef = useRef()` now. – pfinferno Aug 08 '22 at 19:24