asynchronous code to nested synchronous manner in Meteor/React

I have been trying to run data fetching code in a container component and pass it to the display one to reduce using hooks and load time. I tried both await/sync and Meteor’s wrapAsync Here is its Docs but I admit I dont really understand this function.

N.B: The code is pseudo code that explains the basic structure and functionality I need to apply, everything has been imported properly. The code structure and order is the same as the actual code. Thats what matters

Current Result

display component errors out as undefined because the data or t1Doc are empty

Container async/await

const Container = withTracker(({ id, ...rest }) => {   const t1Handle = Meteor.subscribe("table1");   const t2Handle = Meteor.subscribe("table2");   const isLoading = !t1Handle.ready() && !t2Handle.ready();   const fetchT1Documents = async () => {   const t1Doc = await t1Collection.findOne(query);   let t2Doc;   const fetchT2Documents = async () => {     t2Doc = await t2Collection.findOne(t1Doc.FK);   }   fetchT2Documents();   parseXmltoJs(t1Doc, (err, result) => {     fetchAjaxData(result,t2Doc)     .then((data) => {     return {       isLoading,       t1Doc,       t2Doc,       data     }   }) });   }   fetchT1Documents();        return {     isLoading,     t1,     ...rest,   }; })(WithLoading(displayComponent)); 

Loader

const WithLoading = (Comp) => ({ isLoading, children, ...props }) => {   if (isLoading) {     return <Loader />;   } else {     return (       <Fade in={true} timeout={500}>         <div>           <Comp {...props}>{children}</Comp>         </div>       </Fade>     );   } };  export { WithLoading }; 

sorry for the bad editing

Add Comment
1 Answer(s)

A few tips on this one…

You can make a publication that publishes more than one collection/query, eg table1 and table2. It returns a single handle, that is ready when both collections have data.

No need to do an await on the collection.findOne() calls – these are calls to minimongo (client side cache), and will return either null when the subscription is loading, and will return the data otherwise.

The pattern you are using is excellent, and allows separation of display logic from the grubby data layer 🙂

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.