1. 16
    Using TypeScript and Redux to Model the Different States of our Checkout Form
    1m 52s

Using TypeScript and Redux to Model the Different States of our Checkout Form

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

This lesson uses the excellent classnames library to apply different formatting to our checkout page based on the current state of our form. To model those states we use TypeScript's string literals, which are great for simple situations like this. This lesson sets us up nicely for responding to all the actions generated by our checkout thunk, which we'll explore in the next lesson.

There's a great discussion here about when to use string literals over enums: https://stackoverflow.com/questions/49761972/difference-between-string-enums-and-string-literal-types-in-ts

Jamund Ferguson: [0:00] In your IDE, open up cartSlice.ts. At the top of the file, add a new type called CheckoutState, which will be a string literal containing three possible states -- "LOADING", "READY", and "ERROR".

[0:11] Then in our CartState interface, add checkoutState as a property, using that new type as its type. Then down in initialState, add checkoutState and set the default checkoutState to "READY".

[0:23] Open up a terminal window and type npm install classnames. With that installed, open up Cart.tsx. At the top of the file import classNames from "classnames". You'll notice I use an uppercase N here just to be more consistent with JavaScript style.

[0:38] Then in our selector block here, type const checkoutState = useAppSelector(state ==> state.cart.checkoutState). Right before our return statement in our cart component, type const tableClasses = classNames, and then pass in an object. We're going to use the computed property syntax [styles.table]: true, [styles.checkoutError]: checkoutState === "ERROR" and [styles.checkoutLoading]: checkoutState === "LOADING".

[1:12] This classNames library is going to give us a single class name string that includes multiple class names in it, based on what we've passed into this object. We had to use computed property syntax because these class names are generated by CSS modules and we don't know what they're going to be until build time. Now that we've generated our class name, let's grab that and replace styles.table here with tableClasses.

[1:33] If we head into our Shopping Cart, you can see that it looks totally normal. If we head back to cartSlice.ts and set the checkoutState to "LOADING," if we add some products and head back to the cart, you can see the entire cart is greyed out, like we'd expect in a loading state.

[1:46] If we change this to "ERROR," add some products, we wrap our table in a red outline indicating there's some kind of error with the form.