Meteor + Svelte and Optimistic UI

I’ve just completed my first Svelte and Meteor App. It’s a simply “todo-list-like” app and works pretty well.

Now I have a doubt. I read that if you’d like to use Optimistic UI, you have to share the methods file both in the server and client.

I read old posts in this forum that explain this thing but, frankly, I’m yet confused.

Can you explain me the right way to accomplish this?

Thanks :slightly_smiling_face:

When you call a Meteor method that is defined on the client as well as the server it gets executed on both. When the client side executes you can perform optimistic UI actions.

For example, let’s say you have the following method

Meteor.methods({
 someMethod(arg1) {
  if(this.isSimulation) {
   // this code runs on the client
   // you could show a spinner, for example
   showPageSpinner(true);
  } else {
   // this code runs on the server
   const result = {success: true, result: arg1};
   return result;
  }
 },
});

Then you call the function on the client

Meteor.call('someMethod', 'the argument', function(err, res){
 if(err) {
  console.error(err);
 } else {
  showPageSpinner(false);
  console.log(res);
 }
});

What do you mean “defined on the client as well on the server”? Do I have to write the methods two times?

Regards Optimistic UI: I’d like to see the result of a write action immediately. How can I do it?

The way I have written the example you only write the method once and make sure they are imported both on client and server. You can also have separate method body declarations, totally up to you.

No you don’t. You write it once and import the code in both client and server environments.

Meteor, then, is smart about this and uses the method’s code to “mimick” or replicate the expected changes on data by that method to the existing documents in client’s MiniMongo. If the actual changes on the documents done by the server match the optimistic changes already present in your client’s dataset, it will seem as if the operation was instant. If the changes differ, your collections will reflect that once the actual updates flow through your subscriptions to the client. So, if eg. your server denies a delete for a reason the client could not anticipate, the deleted document will just pop back up on the client after it “seemed” to get deleted.

1 Like

All right!!

Now It’s clear.
Thank you all, guys! :pray:

1 Like