Search code examples
javascriptreactjsmeteorasync-awaitarray.prototype.map

Checking if !isLoading and state exists with useTracker meteor subscribe and findOne mongo


I normally can do this when I render the react component with an isLoading however if I try to use that to test that a variable is ready it complains that the map is undefined even though in the console it certainly is an array value that I am selecting. The isLoading returns undefined sometimes, and I've tried checking for if isLoading is !undefined and so here I am stuck.

const { leadsBuilder, isLoading } = useTracker(() => {
    const noDataAvailable = { leadsBuilder: [] };

    if (!Meteor.user()) {
      return noDataAvailable;
    }

    const handler = Meteor.subscribe("leadsBuilder");

    if (!handler.ready()) {
      return { ...noDataAvailable, isLoading: true };
    }

    const leadsBuilder = LeadsBuilderCollection.findOne({ _id: params._id });
    return { leadsBuilder };
  });

  if (!isLoading && leadsBuilder) {
    let stateReplace = [];

    leadsBuilder.inputs.map((leadInput, i) => {
      stateReplace.push({ id: i, text: leadInput.name });
    });
  }

Solution

  • You're testing if leadsBuilder is truthy, but your invoking the .map on a property of leadsBuilder.

    You should replace your condition by:

    if(!isLoading && leadsBuilder?.inputs?.length) {
        //your code
    }
    

    The ? test if the variable / property is defined, and then we use length because we want the array to not be empty