Instructor: We start off with a bare-bones React-type script application. We are simply rendering the text, "Hello world," from our application component.
To maintain the state logic of your application, we create an app state DS4. We bring in the usual suspects from MobX, which are the observable and action.
Now we write down our application requirements. We want to store a list of items as strings, maintain a current string for the user, ability to add this current string to the list of items, and, finally, add an option to reset the application into its initial state.
We can model these requirements as a simple application state class. We store a list of items, keep track of a current item, provide a method to change this current item, provide another method to add this current item to the list of items, and, finally, reset the application to the initial state.
Let's create a UI for our application that uses features of the state class. You can make your application complex with ideas like provider and connect and even third-party libraries that add more complex concepts and even more boilerplate, but really, with MobX you don't need to.
All you need is the observer annotation. To use the state class, you simply bring in the singleton and use it within the render method of your application.
Within the application render method, we go ahead and create a new form. On submit, we prevent the browser default of posting back at the URL and simply call appState.addCurrentItem.
We wire an input to the appStateCurrentItem and appStateChangeCurrentItem method. We provide a button to add the current item to the list by simply invoking the form Submit.
Next we add a button that goes ahead and resets the application to the initial state. Finally, we render out an unordered list of all the items that are currently in the list. If we go ahead and run the application, you can see that we can provide a current item value using the input, submit the form using the enter key, also submit the form using the add button.
Finally, reset the application to the initial state. Notice that you use the application state class button. We really didn't have to do anything special in the UI beyond the simple observer annotation.
Additionally, we get a nice refactorable-type safe experience, as we know all the ways the app state is used in our UI. This simple application state class button is simple to understand and is fundamentally easier to maintain and describe to new developers and maintain for experienced developers in the long run.
Also, if you have complex business logic in this class, you can test this single instance without having to wire it up to React.