Fetch() causing command to execute earlier

I have made a recipe app which has a minor bug. The ingredient listing of the previous recipes and the recipe the user is currently viewing is all getting added up in the DOM as the previous/next recipe buttons are pressed.

While trying to debug, I realized that the Dom elements that are getting created via a function at a later stage, are getting attached to the “result” tag even before the function is called!

The “recipeDetails” function is the function which is getting called for the display of the recipe and the “result” is the tag to which every element is getting attached.

Any idea how to rectify this? I am assuming this has something to do with the asynchronous nature of the fetch method.

CodePen Link : https://codepen.io/K_S_E11/pen/GRxXNGM?editors=1011

The result variable is pointing to the #result div. When you console log that element and look at it in the dev tools’ console it will show the current state of the div, not the state it was in when the console.log was actual executed. By the time you look at it in the console, the first recipe has been added to the div and thus you will see the HTML for that recipe in the div’s innerHTML property. If you want to see the actual value of innerHTML at the time the console.log is executed then you need to log result.innerHTML.

I would recommend you do a console log of the arguments passed into displayRecipe. I think you will see that they are the problem here.

1 Like

@bbsmooth thanks! will try doing that👍🏻

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.