Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Too simple example #2

Open
davidsavoie1 opened this issue Jan 11, 2020 · 1 comment
Open

Too simple example #2

davidsavoie1 opened this issue Jan 11, 2020 · 1 comment

Comments

@davidsavoie1
Copy link

Hi! Thanks for setting up this minimal example of using Meteor Tracker with Svelte! It was really easy to reproduce and get the exciting feeling that this might actually work with so little code!

However, the example is a little bit too simple, in that, most of the time, the function used in the Tracker.autorun needs to be parameterized with values that might change. So I developped another method, extracting the Tracker logic into a separate file.

withTracker.js

import { Tracker } from "meteor/tracker";
import { onDestroy } from "svelte";

export default function withTracker(trackedFn) {
  const computation = Tracker.autorun(trackedFn);

  onDestroy(() => {
    computation.stop();
  });

  return computation;
}

App.svelte (script only)

import withTracker from "./withTracker.js";
import { Actions } from "/collections";

let today = false;
let completed = false;

let actions = [];
const actionsComputation = withTracker(() => {
  actions = Actions.find({ today, completed }).fetch();
});

$: {
  actionsComputation.invalidate([today, completed]);
}

withTracker returns the computation instance. The Svelte component then sets up a reactive statement that will invalidate it if any of the parameters change. computation.invalidate takes no argument, so I pass the parameters there for concision.

And it works like a charm! What are your thoughts on this approach? It seems almost too easy... Am I missing something obvious?

@klaussner
Copy link
Member

Thanks for posting this example, @davidsavoie1. I agree that the current Tracker example is too simple and should be updated to be more practical. 👍 The only drawback I can think of with your approach is that the arguments today and completed have to be used in both the Tracker function and the reactive statement, which could lead to bugs if one is updated but not the other.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants