I have a video. suppose the length of the video is 0:10 sec (10 second). Also have array of array data structure like [[100,100],[20,20],[50,50],[10,10],[30,30]]. In the every sub array have two values which is represent the [x,y] coordinates. The length of the parent array is equal to the video length. I want to do that, whenever start the video the loop is start to iterate until the video length , also iterate the array of array until the length of video length and save the x and y coordinate in the state variable. How can i do it. please give the solution.
video length :0:05 sec
array of array :[[100,100],[20,20],[50,50],[10,10],[30,30]]
You can use a function with setTimeout. If the second variable is less than the video length call the function again.
The function is initially called with useEffect which is called once when the component is mounted (empty dependency array).
In this working example I'm mapping over the state and log each coordinate pair just to show how the output works.
const { useEffect, useState } = React;
// Pass in the data to the component
function Example({ videoLen, data }) {
// Initialise the state with an empty array
const [ coords, setCoords ] = useState([]);
// The looping function uses `setTimeout`.
function loop(sec = 0) {
// Update the state by preserving the previous
// state and adding the array stored at data[sec] to it
setCoords(prev => [ ...prev, data[sec] ]);
// If the sec variable is less than the
// length of the video call loop again with
// an incremented sec variable
if (sec < +videoLen - 1) {
setTimeout(loop, 1000, ++sec);
}
}
// Call `loop` once when the component
// is mounted
useEffect(() => loop(), []);
// `map` over each coord pair in state
// and add return some JSX
return (
<div>
{coords.map(coord => {
const [ x, y ] = coord;
return <p>X: {x} Y:{y}</p>;
})}
</div>
);
};
const data = [[100,100],[20,20],[50,50],[10,10],[30,30]];
ReactDOM.render(
<Example videoLen="5" data={data} />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>