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}/>
);
CodePudding user response:
I found that the error occurs because the BannerCarousal component is trying to find the ref.current
. The ref.current
is gone when the user is redirected to the Login screen. That's why the error null is not an object
occurs. This is the solution that I did:
export const BannerCarousel = React.forwardRef((props, ref) => {
let index = 0;
const totalIndex = props.data.length ;
useEffect (() => {
setInterval (() => {
if(ref.current !== null) {
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>
);
});
CodePudding user response:
Where you are referencing the useRef flatListRef ? it seems like its not referencing any Valid Node. So it returns..
TypeError: null is not an object (evaluating 'flatListRef.current.scrollToIndex')
CodePudding user response:
Hey initially ref might not be attached in first render, hence you could have done it like this @Nomel
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)
Anyways your check of not null works fine too :)