Search code examples
javascriptember.jsember-data

Ember send data from component to route and refresh it


I have a route in my Ember app that looks for an email in the URL as a query param and loads data based off of it.

export default Ember.Route.extend({

  queryParams: {
    email: true
  },

  actions: {
    complete (data) {
      this.set('model', data)
    }
  },

  model ({ email }) {
    return this.store.queryRecord('user', { email })
  }

})

The data and action from this route is getting passed to a user-form component:

{{user-form model=model addUser=(route-action "complete")}}

And then the component itself. I’d like to be able to send data from this component to the route, which in turn updates the model:

export default Ember.Component.extend({

  store: Ember.inject.service(),

  email: null,

  actions: {
    async submit() {
      const store = this.get('store')
      const email = this.get('email')
      try {
        await store.unloadAll('user')
        const data = await store.queryRecord('user', { email })
        await this.get('addUser')(data)
      } catch (error) {
        console.log(error)
      }
    }
  }

})

What I want to happen is that when the data is sent from the component to the route action, the model is updated with the new user. It should only have one record at a time (hence the store.unloadAll('user').

Currently I’m not sure how to have a route that can load data via query params as well as data being sent to it from a component.


Solution

    1. Manually setting model data in complete function is not the right way to refresh route.
    2. Component sending data to set model is not the right way refresh route.

    I would encourage you to use queryParams with refreshModel:true

    I modified your code, you please give it try.

    Route file,

    export default Ember.Route.extend({
        queryParams: { email: { refreshModel: true } },
        model({ email }) {
            return this.store.queryRecord('user', { email })
        }
    })
    

    controller file,

    export default Ember.Controller.extend({
        queryParams: ['email'],
        email: true, //default value
        actions: {
            updateEmail(email) {
                this.set('email', email) //setting email property will refresh route with new value
            }
        }
    });
    

    component file,

    export default Ember.Component.extend({
        email: null,
        actions: {
            submit() {
                this.get('updateEmail')(this.get('email'));
            }
        }
    })
    

    while including the component,

    {{user-form model=model updateEmail=(action 'updateEmail')}}