Handling Complex State Management with TypeScript Unions
When we declared the state at the beginning of the useLoadAsyncVideo
Hook, it's initially set as a string
.
Since we want this state to represent different possibilities such as loading
, loaded
, or error
, we can create a State
union and then pass it into useState
:
type S
Transcript
00:00 So, the solution is pretty simple here. When we declare this state up here, it gets declared as String. Now, what we really want is for this actually to be a union of a few different things. We want this to be a union of Loading, Loaded or Error. These are the three different things that this should be.
00:18 And what we can do is actually we can pass this into useState here. And now when that happens, we actually get this state here which is now marked as State. And now when we try to actually set to it or initialize it, then it's going to be one of these options. So, setState Loading, setState Error, setState Loaded. And we get all of these benefits down here.
00:40 So, we can't now check if state is does not exist because this comparison appears to be unintentional. Oh, thank you TypeScript. The state and does not exist have no overlap. So, this doesn't kind of belong on here. And also, when we get to the bottom of here, then really we've run out of options.
00:59 So, now state, if we take a look at it, it's actually never because we've checked if it's Loading, we've checked if it's Loaded and we've checked if it's Errored. So, this is a really, really great pattern for if you're trying to do any kind of complex state management because it lets you figure out all of the different states that can be in your application.
01:18 And we're going to look at another example of this in a minute.