Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I display an object from an array based on timer?

I’m building a music application and I’d like to display content from a specific object in an array based on a start and duration time. Here is an example of my data.

[
{
id: 1,
content: 'hello how are you',
start: 0,
duration: 10
},
{
id: 2,
content: 'hello Im fine',
start: 15,
duration: 10
},
{
id: 3,
content: 'hope you you have a great day',
start: 30,
duration: 10
}
]

So basically I will be using the currentTime property on the audio element, and based on this property I will display the appropriate message on content property. Currently I’ve been able to match the content start with the currentTime, but unable to figure out how to display over the duration. This is pretty much what I have:

const PodcastDetail = ({ podcast }) => {
    const [currentMarker, setCurrentMarker] = useState({});
}

  const handleMarker = (podcast) => {
        let marker = podcast.markers.find((mark) => {
            return mark.start  == currentTime;
        })
        setCurrentMarker(marker)
    }

As you can see I’m just returning the object from the array which matches the current time, however it disappears once the currentTime changes. I’d like to display that content throughout its duration.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

however it disappears once the currentTime changes.

It’s because you just change your state with a null (no object found) 🙂
You can basically do something like that:

const handleMarker = (podcast) => {
    let marker = podcast.markers.find((mark) => {
        return mark.start  == currentTime;
    })
    if (marker) setCurrentMarker(marker)
}

So if no marker match your currentTime, you don’t update the state, so you leave the previous marker in your state

== EDIT ==

And if you want to use your duration you should change your condition to

const handleMarker = (podcast) => {
    let marker = podcast.markers.find((mark) => {
        return (currentTime >= mark.start) && (currentTime <= (mark.start + mark.duration));
    })
    setCurrentMarker(marker)
}

In this case I remove the condition to setCurrentMarker because you indeed want to set it at null if nothing matches the condition

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading