Transcript
00:00 So we've got our getQueryParam, we're passing that to our use state, so that's initializing based on that current param. So we just need to get that query param when the user is hitting forward and backward and reset the query to be whatever the query param is after the user has hit forward and backward, right?
00:17 So like here, we type in cat, hit submit, everything's working fine, I hit back, and now we need to get that query param again and set the query value to that so that it no longer includes cat, right? That's all that we're trying to do here. Pretty straightforward.
00:33 We're going to add this use effect right here, and you'll notice we have an empty dependency array. We have no dependencies. We aren't dependent on anything to resubscribe to the pop state event. We're just going to subscribe to it the one time.
00:50 So let's say window.addEventListener, pop state, setQuery, and that should take care of us for now. There are a couple of problems with this still, but this will take care of us for now. So we're listening to whenever the pop state event fires, so the user has clicked the forward or backward button.
01:08 Now we're going to reset the query to getQueryParam. Now, you'll notice we're actually just passing the function, which is kind of interesting. So use state accepts a function. The state setter also actually can accept a function. So we can pass it the state itself, so we could actually
01:27 just call it, but we can also pass it a function, and then React will call that function to retrieve the state. So there you go. That works nicely. So we save this, and now if I type in cat, hit Submit, and then go back, oh my goodness. Look at that happening, all because we are now listening
01:45 for the event and keeping our query updated to whatever the URL says that query should be whenever the user hits forward and backward. So solid.