Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท Ember Data and Models

Querying and Caching

Filter, sort and paginate with store.query, read the cache with peek, control reloads with findAll options and include, and avoid common caching surprises, with runnable stand-ins.

Lists of records are usually too big to load whole. You need searches, filters, sorting and pages, and you need to understand when Ember Data goes to the server and when it answers from its cache. Both topics decide whether your app feels instant or sluggish, and whether it ever shows stale data.

Real versus stand-in. Store calls are real Ember Data, read-only here. The runnable blocks simulate a server and a cache in plain JavaScript to show request counts and pagination.

store.query: asking the server

query sends your parameters as a query string and returns the matching records:

JavaScript
// GET /posts?filter[status]=published&sort=-created-at&page[number]=2&page[size]=10
const posts = await this.store.query('post', {
  filter: { status: 'published' },
  sort: '-created-at',
  page: { number: 2, size: 10 },
});

The meaning of filter, sort and page is up to your server; Ember Data just encodes the object. The result is a record array that is not kept up to date with the store's other changes: it is a snapshot of what the server returned. Related calls:

  • queryRecord('post', { slug: 'hello' }): expects a single record back (useful for lookup by something other than id).
  • findAll('post'): loads everything; fine for small lookup lists (countries, categories), risky for large collections.

Server metadata (total pages, counts) comes back in the meta and links parts of the JSON:API response, and the result keeps them:

JavaScript
const result = await this.store.query('post', { page: { number: 1, size: 10 } });
result.meta.total;   // for example 87
result.links.next;   // URL of the next page, if provided

Query parameters in the URL

Searches should be bookmarkable, so keep the criteria in query parameters of the route (see Query Parameters and Loading States) and turn them into a store.query:

JavaScript
// app/routes/posts.js
export default class PostsRoute extends Route {
  @service store;

  queryParams = {
    page: { refreshModel: true },
    status: { refreshModel: true },
  };

  model({ page, status }) {
    return this.store.query('post', {
      filter: status ? { status } : undefined,
      page: { number: page, size: 10 },
    });
  }
}

With refreshModel: true the route re-runs its model hook when the parameter changes, and the template re-renders with the new page. Always give pages a stable sort order, or records will jump between pages.

JS Stand-in: filter, sort and paginate

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

No output.

Reading the cache: peek and live record arrays

peekAll('post') returns a live array of every post currently in the store. It updates when records are created, loaded or unloaded, so it suits "what the app knows right now" lists, such as showing a new draft instantly. It never makes a request, so pair it with a findAll or query that loads the data.

JavaScript
get drafts() {
  return this.store.peekAll('post').filter((post) => post.status === 'draft');
}

The array is live but the filter result is a fresh plain array each time the getter runs. For repeated expensive use, wrap it with @cached (see Derived State: Getters and @cached).

Cache behavior of the finders

Call Cache hit? Network
findRecord('post', 1) Returns cached record at once Reloads in the background if it may be stale
findRecord('post', 1, { reload: true }) Waits for the server Always
findRecord('post', 1, { backgroundReload: false }) Cached record only None if cached
findAll('post') Cached list at once Background refresh
findAll('post', { reload: true }) Waits for the server Always
query(...) Never reused Every call
peekAll / peekRecord Cache only Never

Practical advice:

  • Use reload: true when correctness beats speed (an account balance, an inventory count).
  • The default background reload gives instant screens with fresh data a moment later; the template simply updates when the data arrives.
  • After a mutation elsewhere on the server (another user, a cron job), call record.reload() or refresh the route.
JS Stand-in: cache with background reload

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

No output.

Include, sparse fieldsets and avoiding N+1

If a list shows each post's author name, loading the authors one by one makes N extra requests. Ask for them together:

JavaScript
this.store.query('post', { include: 'author', page: { size: 10 } });

The server sends authors in the included section, the store caches them, and post.author resolves instantly (also for async: false relationships, see Relationships). Fetch only the fields you need with a sparse fieldset if your API supports it: fields: { posts: 'title,created-at' }.

Pushing data into the store yourself

Real-time updates (WebSocket, server-sent events) can add data without a request:

JavaScript
this.store.push({
  data: { type: 'post', id: '5', attributes: { title: 'Changed on the server' } },
});

push accepts a JSON:API document, updates the cached record (or creates it), and every screen showing it refreshes. Use unloadRecord() to remove a record from the cache without touching the server.

Common mistakes

  • Expecting query results to update live. They are snapshots; use peekAll or re-run the query.
  • No stable sort with pagination. Page boundaries shift and records repeat or vanish.
  • Using findAll on a huge table. Paginate with query instead.
  • Showing cached data as fact. If freshness matters, use reload: true.
  • Requesting related records one by one. Use include.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between peekAll and findAll?

    peek methods never make requests. find methods go through the store's loading rules.
  2. 2. A route should reload its list when the page query parameter changes. What do you add?

    With refreshModel the router re-runs the model hook when the parameter changes.
  3. 3. How do you force findRecord to wait for fresh data?

    The reload option skips the instant cached answer and waits for the server.
  4. 4. How do you avoid one author request per post in a list?

    include asks the server to send the related authors with the posts, in one request.

Summary

  • query sends filter, sort and page parameters to your server and returns a snapshot with meta and links.
  • Put search criteria in route query parameters and use refreshModel to reload.
  • peekAll and peekRecord read the live cache; findRecord and findAll return cached data and refresh in the background unless you pass reload.
  • Use include to load related records in one request.
  • store.push and unloadRecord manage the cache directly for real-time updates and cleanup.

Next: Services in Ember