Resetting query parameters immediately after entering a route in Ember.js

André Joaquim
Trouva Product Blog
2 min readJun 22, 2020
Thanks to Tom Grünbauer for sharing their work on Unsplash

At Trouva, we’re constantly faced with different challenges. One of them arose this past week, while building another amazing feature for our beloved retailers, whose dashboard is built using Ember.js. The requirement was the following:

After a user successfully completes an action in the Product page, we want to display a special message in a modal after transitioning to the Catalogue page.

As we didn’t want to globally store such a ephemeral state (e.g. in a Service), we opted to go with a query parameter when transitioning from the Product page back to the Catalogue page. We defined this parameter as showSpecialMessage.

If you’re reading this article, you must be familiar with Ember.js, so I don’t need to tell you I’ve generated a controller for the Catalogue’s route and that I’ve added the showSpecialMessage query parameter with a default value of null. But, just in case you’re wondering how it looks…

We’ll now need to use the showSpecialMessage in our template to conditionally render the message’s modal, and we’ll achieve that by simply returning it in the route’s model hook.

What you might notice is that the query parameter is still present in the URL, even after the message is displayed and the modal’s dismissed. If the user refreshes the page, he shouldn’t see the message again. Therefore, we need to reset the query parameter after the user visits the page. We achieve that by using the afterModel hook.

By transitioning to the same route, and by omitting the refreshModel: true from the query parameter’s configuration, we successfully reset the showSpecialMessage query parameter immediately after the user enters the Catalogue route! 🎉

Additionally, we’ve enabled replace for this query parameter. From the Ember.js’ documentation:

By default, Ember will use pushState to update the URL in the address bar in response to a controller query param property change. If you would like to use replaceState instead, which prevents an additional item from being added to your browser's history, you can use replace: true

This will also prevent users from accidentally seeing the message’s modal when they click back on their browsers.

I hope you’ve enjoyed this small article about resetting query parameters after entering a route in Ember.js! It’s as simple as using afterModel and replace: true. Feel free to leave any comments or suggestions!

--

--