Advanced Hooks 8 exercises
Problem

Using Discriminated Unions in useState

We're back with our UseLoadAsyncVideo hook, just with a slightly different representation of how useState works.

Instead of just having loading or loaded, we're now using an object with status: "loading":


export const useLoadAsyncVideo = (src: string) => {
const [state, setState

Loading exercise

Transcript

00:00 In this exercise, we're back with our UseLoadAsyncVideo hook, except we've decided to go for a slightly different representation of how this useState works. Instead of just having loading in there or loaded in there, we're actually now using an object with status Loading.

00:15 Except, I mean, this is working great, except for the cases where we want an error. Because when we want an error here, we basically want to say, okay, whenever there is an error, we want there to be an error present on that object. So we have a piece of state that's kind of dependent on a status.

00:34 And here we've got some stuff in here that's supposed to be erroring, where we have a setState status Error. That's supposed to be an error because it's not including an error. Here we've got one which is status Loading, which is basically supposed to be erroring because it's like it shouldn't have an error on there if we're loading.

00:51 And here it's got status Loaded where it should be erroring because we've got an error and it's loaded. You get the idea. We also got a check down here to see if if state.status equals error, we want to console.log this error. And this is currently erroring because property error does not exist on type status string.

01:08 So your job is to try to figure out a way that we can represent this with a type and then use this in our useState to type it properly. Good luck.