Advanced Hooks 8 exercises
Problem

Using TypeScript to Manage Complex State

Let's explore how TypeScript can be used to make complex state management easier.

Here we have a useLoadAsyncVideo hook that is designed to load and play a video based on a given source:

export const useLoadAsyncVideo = (src: string) => {
  const [state, setState] = useState("loadi
Loading exercise

Transcript

00:00 Here, we're going to look at how you can use TypeScript to make complex state a little bit easier to deal with. We have a Use Load Async Video hook. What this hook does is it basically, in a use effect, you can pass it a source, which is the source of the video you want to load. What it's going to do is it's going to fetch the video via the source and return a blob.

00:20 That blob is then going to append the video to the DOM and play. Now, there are a few things that we need to take in mind here. When we first start this loading process, we're going to set the state to Loading. That means we can show a loading spinner or something. We're also going to add a cancellation flag, but I'll get to that in a minute.

00:37 So when we finally append the video to the DOM and play it, then we can set the state as Loaded because we know the video is there. Finally, if we have kind of an error in loading the video or even in fetching the video, then it's going to Error instead.

00:52 And finally, if it's cancelled at any point, so basically here we have a cancelled false, so it's not cancelled. Then when we kind of change to a new source, we can mark the cancel flag as true and it's not going to do anything in either of these branches. That's really crucial.

01:09 So this is all good, except for the fact that, in fact, when you go to do this exercise, you don't need to actually change any of this code up here in the use effect. Or basically from here to here, you won't need to change. Use effect is fine. But there's an issue, which is actually this state here is just typed as String.

01:28 So these states that may or may not exist, actually, like down here, it would be great if we could return a loading spinner if the state is loading. And we should also be able to assert down the bottom here that we've covered all the cases, but actually state all the time here is just String.

01:43 So your job is to try to figure out a way that we can make this a bit more strongly typed and get some behaviour in here, like, or get some guardrails so that we know the behaviour will perform as expected.