How to wait `Template.onCreated` before `Render`?

I would to wait Template.onCreated() finish and then go to Rendering like this

Template.onCreated(async function() {
   let data = await getData.callPromise(.......)
   .............
  console.log('created')
})

Template.onRendered(function() {
  ..................
  console.log('rendered')
})

The result

rendered
created

Please help me

That’s not how async works.

What do you want to achieve?

I would like to get data complete before Rendered
Bc I use this data on Rendered

let data = new Reactive....

Template.onCreated(async function() {
   data = await getData.callPromise(.......)
   .............
  console.log('created')
})

Template.onRendered(function() {
  // Use data variable in this block
  let new = data...
  ..................
  console.log('rendered')
})

The reason that’s not working it that the onRendered is a non-reactive context. Your ReactiveVar or ReactiveDict will not be ready until the await completes and that will be too late for onRendered.

You can make onRendered into a reactive context, but it’s likely that it will not give you what you want.

Why do you want to use a reactive variable in the onRendered? That’s normally when you would use a template helper.

I would like use Reactive data in onRender to config jQuery value (DateTime Picker)?

Then you will have to set up an autorun in the onRendered, so it will wait until the data is ready. However, you should be aware that it may still not work as expected if you have any reactive elements in your HTML template which your jQuery plugin relies on.

Something like this may work:

Template.xxx.onCreated(async function() {
  this.result = new ReactiveVar();
  this.result.set(await getData.callPromise(.......));
})

Template.xxx.onRendered(function() {
  this.autorun(() => {
    const data = this.result.get();
    if (data) {
      // set up jQuery plugin here
    }
  });
});

However, you don’t need async/await here. You could also do:

Template.xxx.onCreated(function() {
  this.result = new ReactiveVar();
  Meteor.call('someMethod', (err, data) => {
    if (err) {
      //
    } else {
      this.result.set(data);
    }
  });
});

Template.xxx.onRendered(function() {
  this.autorun(() => {
    const data = this.result.get();
    if (data) {
      // set up jQuery plugin here
    }
  });
});
2 Likes

Wow, It is great solution.
I missed the this.autorun().
I will try soon :blush:

1 Like

Now work fine

// onRendered

  let $tranDate = $('[name="date"]')

  // Check date picker
  this.autorun(() => {
      const lastTranDate = this.lastTranDate.get();

      if (lastTranDate) {
        $tranDate
        .data('DateTimePicker')
        .minDate(moment(lastTranDate).add(1, 'days').startOf('day'))
      }
  });