Search code examples
reactjsmeteormeteor-tracker

Why map does not work under Tracker.autorun of Meteor?


Recently I found out that if I apply the map function to my array inside Meteor's Tracker.autorun function it does not work, I have been wondering why? I tried making static array even that doesn't work.

   renderMyBooks() {
        Tracker.autorun(() => { 
            Meteor.subscribe("ziglerNata")
            console.log(Meteor.userId());
            const myBooks = BooksInfo.find({ userId: Meteor.userId() }).fetch();
            //const myBooks = [1,2,3,4,5];
            console.log(myBooks);
            return (myBooks.map(book => {
                    return (
                        <div key={book._id} className="book-info">
                            <div className="book-info-content">
                                <div className="book-info-content-t-a">
                                    <h3>{book.title} </h3>
                                    <h5>{book.author}</h5>
                                </div>
                                
                            </div>
                        </div>
                    )
                })
            )
        })
    }

Solution

  • I would suggest a different approach. This may not directly answer your question as to why Tracker.autorun is not working as you expected, but I think will help you more than if looking for an answer to your original question.

    I believe the recommended pattern for using reactive data sources in meteor with react is to use useTracker. Here is your code rewritten in that pattern:

    import { useTracker } from 'meteor/react-meteor-data';
    
    const MyBooks = () => {
      const myBooks = useTracker(() => {
        Meteor.subscribe("ziglerNata")
        console.log(Meteor.userId());
        return BooksInfo.find({ userId: Meteor.userId() }).fetch();
      }, []);
    
      console.log(myBooks);
      return (myBooks.map(book =>
        <div key={book._id} className="book-info">
          <div className="book-info-content">
            <div className="book-info-content-t-a">
              <h3>{book.title} </h3>
              <h5>{book.author}</h5>
            </div>
          </div>
        </div>
      ));
    }