this my code:
export default function VideoPlayer() {
const videoPlayerRef = useRef(null);
const [status, setStatus] = useState({});
const [totalDuration, setTotalDuration] = useState(null);
return (
<View style={styles.container}>
<Video
ref={videoPlayerRef}
source={'https://samplelib.com/lib/preview/mp4/sample-5s.mp4'}
onLoad={status => setTotalDuration(() => status)}
/>
<Text style={styles.timestamp}>{totalDuration.durationMillis}</Text>
</View>
);
}
I expect to get total video duration from Video parameter onLoad. However I get an error code:
<Text style={styles.timestamp}>{totalDuration.durationMillis}</Text>
Outputs: Cannot read properties of null (reading 'durationMillis')
. Any ideas what’s wrong there?
2
Answers
The totalDuration state is initialized with a null value, you should handle the possibly undefined case of the object.
The issue in your code is that you’re trying to access the durationMillis property of totalDuration before it has been set. Initially, totalDuration is set to null, and it’s only updated inside the onLoad callback of the Video component. Since the onLoad callback is asynchronous, it takes some time for the totalDuration to be updated, and during that time, you’re trying to access its properties.
To fix this issue, you can add a conditional rendering check to display the totalDuration.durationMillis only when it’s available. Here’s an updated version of your code:
In this updated code, I’ve added a check for totalDuration before rendering the component. The component will only be rendered when totalDuration has a value, preventing the error you encountered. Additionally, I’ve changed the source prop of the Video component to use an object with uri property instead of a string.
Make sure to handle other possible error scenarios and customize the code further to fit your specific requirements.