How do I get the 'Next video' from within an array after clicking/watching a video in React

Viewed 53

In my React app, from the api I can query a list (array) of videos.

How do get the 'Next video' from within an array after clicking a video?

The flow is as follows:

I get the videos from GraphQL with useQuery hook:

const { previousData, data: myVideos = previousData, loading, fetchMore } = useQuery<
    GqlResponse,
    Args
  >(GET_VIDEOS, {
    errorPolicy: 'all',
    notifyOnNetworkStatusChange: true,
  });

Then I can return a list of video teasers:

        {myVideos.map((video) => (
          <VideoTeaser
            key={video.uuid}
            title={video.title}
            url={video.uuid}
            thumbnail={video.thumbnail}
          />
        ))}

With another GraphQl query, I query the video based on uuid:

const { data } = useQuery<GqlResponse, VideoArgs>(GET_VIDEO, {
    variables: {
      uuid: id,
    },
    errorPolicy: 'all',
  });

To the player I pass the uuid so it knows which video to play.

id (above in the GQL variable) is coming from a query param: const id = queryParams.videoId as string;

After clicking a video teaser from the array list it sends the uuid to the query param in the url: <Link {...linkProps} to={url}>

Then in another div (in an overlay) it plays the clicked video from the list in an overlay in the player:

   <Player
      uuid={videoData.uuid}
      thumbnail={videoData.image)
      }
      autoplay
      onEnd={onVideoEnd}
    />

So in every overlay the current video plays and in a sidebar (next to the current video, always the same list of teasers is rendered (always with the same array index and order).

1 Answers

Since you always know the currently played video by it's uuid (id), you can use Array.findIndex() to find it's current index in the videos array (myVideos).

const id = queryParams.videoId
const currentIndex = myVideos.findIndex(o => o.uuid === id)
const nextIndex = Math.max(currentIndex + 1, myVideos.length - 1) // the index can't go beyond the last item
const nextId = myVideos.of(nextIndex).uuid

And you can use the same idea for previous item.

If you want next to be cyclic - jump to the first item if current is last item, use the remainder operator to find nextIndex:

const nextIndex = currentIndex + 1 % myVideos.length 
Related