Search code examples
javascriptember.jsember-dataember-cli

How do I update data in the service store in Ember?


I created a service where I declared the store:

store.js:

import Service from '@ember/service';

export default class StoreService extends Service {
  store = {
    lang: 'EN'
  }
}

I also got access to the store from the route:

first.js:

import Route from '@ember/routing/route';
import { inject } from '@ember/service';

export default Route.extend({
  store: inject(),
  model() {
    console.log(this.store);
    return this.store;
  }
});

And the template. first.hbs:

<div class="wrapper">
  <h3>First</h3>
  <hr class="gold">
  <p><button type="button">CN</button></p>
  {{model.store.lang}}
</div>

{{outlet}}

Please tell me how you can change the data in the store (set lang to "CN") from the route by pressing the "CN" button?

Regards.


Solution

  • If you are usign ember >= 3.16. In your store.js track the state like

    @tracked store = {
      lang: 'EN'
    }
    

    then in your first.hbs add to the button

    <button {{on "click" this.changeLanguajeToCN}} type="button">CN</button>

    and finally in your controller (you need to create this file) first.js

    import Controller from '@ember/controller';
    import { inject as service } from '@ember/service';
    import { action } from '@ember/object';
    
    export default class FirstController extends Controller {
      @service store;
    
      @action changeLanguajeToCN () {
        this.store.store = {...this.store, lang: 'CN'}
      };
    }