useTracker returning empty array

Hello

This is my first time using Meteor and I was trying to follow the React tutorial, but in the part where they fetch the example data from the server, useTracker appears to be returning an empty array.

Here is the code of the main.js file in server folder:

import { Meteor } from 'meteor/meteor';
import { TasksCollection } from '/imports/api/TasksCollection';

const insertTask = taskText => TasksCollection.insert({ text: taskText });

Meteor.startup(() => {
  if (TasksCollection.find().count() === 0) {
    [
      'First Task',
      'Second Task',
      'Third Task',
      'Fourth Task',
      'Fifth Task',
      'Sixth Task',
      'Seventh Task'
    ].forEach((task) => insertTask(task))
  }
});

And here is the code of the App.jsx in client folder:

import React from 'react';
import { useTracker } from 'meteor/react-meteor-data';
import { TasksCollection } from '/imports/api/TasksCollection';
import { Task } from './Task';

export const App = () => {
  const tasks = useTracker(() => TasksCollection.find({}).fetch());

  return (
    <div>
      <h1>Welcome to Meteor!</h1>

      <ul>
        { tasks.map(task => <Task key={ task._id } task={ task }/>) }
      </ul>
    </div>
  );
};

The tutorial says that after this, the tasks defined in the main.js file should appear in screen inside a list, but in my case nothing appeared. With a console log I realized that const tasks = useTracker(() => TasksCollection.find({}).fetch()); is returning an empty array.

You can see that part of the tutorial here

What is wrong?

What does your .meteor/packages file look like? Does it include autopublish and insecure?

No, it doesn’t. Do I need to install them?

If you want to keep following the tutorial step by step, then install them with

meteor add autopublish
meteor add insecure

Step 1 of the tutorial has you create the app with the —prototype flag which would have installed these two packages automatically. They help you prototype quickly.

Later in the tutorial, you’ll actually uninstall these packages and learn why.

3 Likes

I understand. I forgot the -prototype flag when creating the project. Thank you very much!

2 Likes

Hi there,

just for you to understand what is missing, in Meteor you can fetch data with publications/subscriptions or with Methods. Your tutorial is based un publications/subscriptions but you don’t seem to have defined any publication on the server and subscription on the client. This is why you need autopublish but this package is something you only use now while learning Meteor. It has no much use in dev/production where you have to be very mindful with the data you publish and subscribe to.
I suspect at some point you will be asked to remove autopublish and insecure and proceed with a publication and subscription.

2 Likes

Thank you for explaining it to me!