Skip to content

Too simple example #2

@davidsavoie1

Description

@davidsavoie1

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions