Okay, let's get started on task number two in our list saving the user search in the app state. Before we dive in, I want to talk a little bit more about forms in react forms are a unique case as native HTML form elements already managed their own internal state. For example, if I type into our search input, the values being stored in the inputs internal state, this raises the question Where should form state be managed in a react app in the React state, or in the inputs internal state, in our case, we're going to be managing our search input value using react state. The first thing we'll need is a place to store the search inputs value. For that I'll create a new state variable called search term, and set it equal to an empty string by default. Next, we need a way to have a search term stay in sync with what the user is actually typing in the search input.
For this we can use the input on change event, which like the name says fires every time the inputs value changes. For quick test, I'm just going to add an event handler function that logs out the inputs value. The event handlers passed in an event object, which is very similar to a native JavaScript event, but it's actually what react calls synthetic events. This synthetic event is a wrapper around the browsers native event that follows the same interface but works identically across all browsers. With that being said, we can access the inputs value at event dot target dot value. Now if you open the console and start typing, we can see that inputs values being logged out as we type.
Next, let's remove the test function and create a proper on change handler method named on search change. And in this method, we'll take the event target dot value and set our search term state equal to it. then update the search inputs on change event to call our new on search change handler. Let's go ahead and try to type something into our search. It looks like our change has created an error that occurs when you type into the search input. If you recall, we've seen the same error before it is occurring because we forgot to bind on search handler to the component.
This is the same thing we had to do for the on tell joke handler before let's go ahead and fix that up. Perfect now typing into the search input works without air. Just to ensure that a search term is being saved, let's temporarily render it to the screen. Now we can see that as we type, the search term value is being updated as well. With the search term successfully being saved in app state, we can consider this task complete. Next up is turning in a search to happen on form Submit.