I created an auto scroll flatlist for the home screen. When the user logout, it would direct the user to the login screen. The problem is that I got TypeError: null is not an object (evaluating 'ref.current.scrollToIndex')
when the app direct the user to the login screen. What happen and how do I resolve it?
Auto scroll flatlist component:
export const BannerCarousel = React.forwardRef((props, ref) => {
let index = 0;
const totalIndex = props.data.length ;
useEffect (() => {
setInterval (() => {
index = index + 1;
if(index < totalIndex) {
ref.current.scrollToIndex({animated: true, index: index})
} else {
ref.current.scrollToIndex({animated: true, index: 0})
index = 0;
}
}, 3000)
}, []);
return (
<View style={{paddingHorizontal: 10}} >
<FlatList
ref={ref}
data={props.data}
keyExtractor={data => data.id}
renderItem={renderItem}
/>
</View>
);
});
Home.js
const ref = React.createRef()
return (
<BannerCarousel fromLocal={true} data={TopBannerData} ref={ref}/>
);
3
Answers
I found that the error occurs because the BannerCarousal component is trying to find the
ref.current
. Theref.current
is gone when the user is redirected to the Login screen. That's why the errornull is not an object
occurs. This is the solution that I did:Where you are referencing the useRef flatListRef ? it seems like its not referencing any Valid Node. So it returns..
Hey initially ref might not be attached in first render, hence you could have done it like this @Nomel
Anyways your check of not null works fine too 🙂