Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Routing and Templates

Query Parameters and Loading States

Add query parameters to Ember routes for filters, sorting and paging, then handle slow and failing data with loading and error substates, and a custom not-found page.

Two real-world details turn a demo router into a good one. First, screens such as lists need state in the URL: the page number, a search term, a sort order. That is what query parameters are for. Second, data takes time to load and sometimes fails, so the router needs a plan for loading and error states. This lesson covers both.

Real versus stand-in. The route, controller and template code is real Ember, read-only here. The runnable blocks are plain JavaScript stand-ins that reproduce the parsing of query strings and the state machine behind loading and error substates.

Why query parameters?

A page like /posts?page=2&sort=newest&q=ember has a big advantage over keeping the same state in memory: it can be bookmarked, shared and restored with the Back button. Anything that changes what list the user sees, but not which screen it is, is a good candidate. Do not use them for secrets or for transient UI such as "is the menu open".

Declaring query parameters

Query parameters are declared on the controller of the route. Controllers are the one place where Octane still uses them: they hold state tied to a route's URL.

JavaScript
// app/controllers/posts.js
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class PostsController extends Controller {
  queryParams = ['page', 'sort', 'q'];

  @tracked page = 1;
  @tracked sort = 'newest';
  @tracked q = '';

  @action
  nextPage() {
    this.page = this.page + 1;
  }
}

The controller's defaults matter. A parameter that equals its default value is left out of the URL, so /posts and /posts?page=1 mean the same thing and the URL stays clean.

Reloading the model when a query parameter changes

By default, changing a query parameter updates the controller property but does not call model() again. If the data depends on it, tell the route with refreshModel:

JavaScript
// app/routes/posts.js
import Route from '@ember/routing/route';

export default class PostsRoute extends Route {
  queryParams = {
    page: { refreshModel: true },
    sort: { refreshModel: true },
    q: { refreshModel: true, replace: true },
  };

  async model(params) {
    const search = new URLSearchParams({
      page: params.page,
      sort: params.sort,
      q: params.q,
    });
    const response = await fetch(`/api/posts?${search}`);
    return response.json();
  }
}

params includes the dynamic segments and the query parameters, already converted to the type of the default (a number default gives you a number). replace: true replaces the history entry instead of adding one, which stops each keystroke in a search box from filling the Back button.

Using them in a template

JavaScript
// app/templates/posts.gjs
import { LinkTo } from '@ember/routing';
import { on } from '@ember/modifier';
import { hash } from '@ember/helper';

<template>
  <button type="button" {{on "click" @controller.nextPage}}>Next page</button>
  <LinkTo @route="posts" @query={{hash sort="oldest" page=1}}>Oldest first</LinkTo>

  <ul>
    {{#each @model.items as |post|}}
      <li>{{post.title}}</li>
    {{/each}}
  </ul>
</template>

Route templates also receive @controller, the controller instance, in addition to @model.

Because page is tracked, the page updates when it changes and the URL updates with it. The loop is complete: the URL drives the model, the controller keeps the values in sync, and the template shows the result.

JS Query parameters with defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Sticky and scoped parameters

Query parameters are sticky by default for dynamic routes: if you leave posts and return, Ember remembers the last values. Use { as: 'p' } to give a parameter a shorter URL name (queryParams = [{ page: { as: 'p' } }]), and avoid names that collide between routes.

Substates: loading and error

While a model() promise is pending, what does the user see? Ember looks for a loading substate and shows it; if the promise rejects, it looks for an error substate. You create them by naming templates:

JavaScript
// app/templates/loading.gjs : shown while any route is loading
<template>
  <p role="status">Loading...</p>
</template>
JavaScript
// app/templates/posts-loading.gjs : only while the posts route loads
<template>
  <p role="status">Loading posts...</p>
</template>
JavaScript
// app/templates/error.gjs
<template>
  <h2>Something went wrong</h2>
  <p>{{@model.message}}</p>
</template>

The lookup starts at the route that is loading and moves up the tree: first a template named after the route itself (posts-loading), then a loading template inside the parent (posts/loading), and finally the top-level loading. In practice: put one loading and one error template at the root, and add specific ones where a better message helps. The error template receives the thrown error as @model.

You can also take control with the loading and error actions on a route:

JavaScript
// app/routes/application.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';

export default class ApplicationRoute extends Route {
  @action
  error(error, transition) {
    if (error.status === 401) {
      this.router.transitionTo('login');
      return false; // handled: do not show the error substate
    }
    return true; // bubble up to the default error handling
  }
}

(Remember to add @service router; to the route class when using this.router.)

JS A loading and error state machine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A custom not-found page

Add a wildcard route at the end of Router.map (see Router Basics) and give it a template:

JavaScript
// app/templates/not-found.gjs
import { LinkTo } from '@ember/routing';

<template>
  <h2>Page not found</h2>
  <p>Try the <LinkTo @route="index">home page</LinkTo>.</p>
</template>

For a record that does not exist (such as /posts/9999), your model() hook should throw or reject, and an error substate handles it. You can check error.status === 404 and show a friendlier message there.

Common mistakes

  • Forgetting refreshModel. The URL and controller change but the list looks the same.
  • Defaults that do not match the type. A default of '1' (string) gives you strings for numbers; use 1.
  • Using query parameters for private data. URLs end up in logs, history and screenshots.
  • No loading or error template. The user then sees a blank screen on failure.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to a query parameter whose value equals its controller default?

    Defaults are omitted so that URLs stay short and /posts equals /posts?page=1.
  2. 2. What does refreshModel true on a query parameter do?

    Without it, only the controller property changes. With it, the data is reloaded.
  3. 3. Which template is shown while a route's model promise is pending?

    Ember looks up the tree for a loading template. If none exists, the previous screen simply stays until data arrives.
  4. 4. What does the error substate template receive as @model?

    The error object is passed so the template can show a message or react to its status.
  5. 5. Why use replace true for a search box query parameter?

    replace swaps the current history entry rather than pushing a new one.

Summary

  • Query parameters keep list state (page, sort, filter) in the URL; declare them on the controller with defaults.
  • Add refreshModel: true (and replace: true for typing) in the route's queryParams to reload data when they change.
  • Use @query={{hash ...}} on LinkTo to link to a state.
  • Create loading and error templates (root level or per route) so waiting and failure are handled; the error template gets the error as @model.
  • A wildcard route and a not-found template handle unknown URLs.

Next: Components and Arguments