Open In App

Ember.js Service cacheFor() Method

Last Updated : 11 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Ember.js is a popular JavaScript framework used for building web applications. One useful feature of Ember.js is the ability to use services to manage shared data and functionality across different parts of an application. The cacheFor() method is a method available on Ember.js services that allows you to retrieve cached data for a given key.

The cacheFor() method is used to retrieve data that has previously been cached using the cache() method. The cache() method allows you to store data in a service’s cache using a given key, and the cacheFor() method retrieves this data using the same key. Caching data using the cache() and cacheFor() methods can be useful for storing data that is expensive to compute or retrieve, such as data from an API call or a large dataset. By storing this data in the service’s cache, you can avoid the need to recalculate or re-fetch the data each time it is needed, which can improve the performance of your application.

Syntax:

this.cacheFor(key);

 

Parameters:

  •    key: It is the name of the property whose value we want to set.

Return: A Object with the passed key value.

Step 1: To run the following examples you will need to have an ember project with you. To create one, you will need to install ember-cli first. Write the below code in the terminal:

npm install ember-cli

Step 2: Now you can create the project by typing in the following piece of code:

ember new <project-name> --lang en

To start the server, type:

ember serve

Step 3: To create a service, you can use the Ember.js command line interface (CLI) by running the following command:

ember generate service my-service

Example 1: In this example, we have a service that stores data about users in its cache. The service has a getUser() method that retrieves data for a given user ID. If the data for the user ID has already been cached, the getUser() method will retrieve the cached data using the cacheFor() method. If the data is not in the cache, it will be fetched from an API and then cached using the cache() method.

  • app/services/user-service.js

Javascript




import Service from '@ember/service';
import { hash } from 'rsvp';
  
export default Service.extend({
    cache: {},
  
    getUser(userId) {
        let cachedData = this.cacheFor(userId);
        if (cachedData) {
            return cachedData;
        } else {
            return this.fetchUser(userId).then((data) => {
                this.cache(userId, data);
                return data;
            });
        }
    },
  
    fetchUser(userId) {
        // code to fetch data from an API
    }
});
  
// app/controllers/user-detail.js
import Controller from '@ember/controller';
  
export default Controller.extend({
    userService: Ember.inject.service(),
  
    actions: {
        fetchUser() {
            this.get('userService').getUser(123).then((userData) => {
                console.log(userData);
            });
        }
    }
});


Run the app: In the Terminal / Command Prompt enter the following command to run the application:

ember serve

Output: If the fetchUser() action is called and the data for user ID 123 has not previously been cached, the output might look something like this.

{ id: 123, name: 'John Smith', email: 'john@example.com' }

If the fetchUser() action is called again and the data for user ID 123 has already been cached, the output will be the same as before, but the data will be retrieved from the cache instead of being fetched from the API.

Example 2: In this example, we have a service that stores data about different products in its cache. The service has a getProducts() method that retrieves data for a list of product IDs. If the data for any of the product IDs have already been cached, the getProducts() method will retrieve the cached data using the cacheFor() method. If the data is not in the cache, it will be fetched from an API and then cached using the cache() method.

  • app/services/product-service.js

Javascript




import Service from '@ember/service';
import { hash } from 'rsvp';
  
export default Service.extend({
    cache: {},
  
    getProducts(productIds) {
        let cachedData = {};
        let uncachedIds = [];
  
        productIds.forEach((id) => {
            let data = this.cacheFor(id);
            if (data) {
                cachedData[id] = data;
            } else {
                uncachedIds.push(id);
            }
        });
  
        if (uncachedIds.length > 0) {
            return this.fetchProducts(uncachedIds).then((data) => {
                Object.keys(data).forEach((id) => {
                    this.cache(id, data[id]);
                });
                return hash(cachedData, data);
            });
        } else {
            return hash(cachedData);
        }
    },
  
    fetchProducts(productIds) {
        // code to fetch data from an API
    }
});
  
// app/controllers/product-list.js
import Controller from '@ember/controller';
  
export default Controller.extend({
    productService: Ember.inject.service(),
  
    actions: {
        fetchProducts() {
            this.get('productService').getProducts(
                [123, 456, 789]).then((productData) => {
                    console.log(productData);
                });
        }
    }
});


Output: If the `fetchProducts()` action is called and the data for product IDs 123, 456, and 789 have not previously been cached, the output might look something like this.

{ 123: { id: 123, name: 'Product 1', price: 19.99 },
456: { id: 456, name: 'Product 2', price: 29.99 },
789: { id: 789, name: 'Product 3', price: 39.99 } }

If the `fetchProducts()` action is called again and the data for product IDs 123 and 456 has already been cached, but the data for product ID 789 has not, the output might look something like this.

{ 123: { id: 123, name: 'Product 1', price: 19.99 },
456: { id: 456, name: 'Product 2', price: 29.99 },
789: { id: 789, name: 'Product 3', price: 39.99 } }

The data for product IDs 123 and 456 will be retrieved from the cache, while the data for product ID 789 will be fetched from the API and then cached for future use.

Reference: https://api.emberjs.com/ember/release/classes/Service



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads