JSON fetch inside a function

Hello everybody,

I’ll try to call a function in my JavaScript to load a special article and display it in the UX. If I do this without a function directly in the JavaScript everything works fine. Inside the responseObject function the console.log is also perfect but then outside of this the Rezept variable is empty also if I do a return. I really get put of mind, looking for a solution since one week! Thanks a lot for your support and ideas!

var Rezept = Observable();

function getRecipe(recipeURL) {	

  fetch('https://XXX/recipes/api/recipes/51')
                        .then(function(response) { return response.json(); })
                        .then(function(responseObject) { 
                        	Rezept.value = responseObject; 
                        	console.log(JSON.stringify(Rezept));
                        	return Rezept;
                        });
							console.log(JSON.stringify(Rezept));
}

module.exports = {
Rezept: Rezept
}

I reformatted your post a bit. Keep in mind that you can use triple backticks (```) to mark code blocks. :slight_smile:

The problem you’re experiencing might be because nothing subscribes to the Rezept observable in the UX? You can check these docs for more info on this: https://www.fusetools.com/docs/fusejs/observable#subscribing-to-changes-in-observables

Also, both fetch and observables are asynchronous, so the 2nd console.log() you have in your code might be executed before there is any data in the Rezept variable.

Hi Remi,

thanks for your styling.

I use the Rezept in the UX of the RecipePage like you can see below. Everything is working fine if I’m loading it directly in the JavaScript without calling it in a JavaScript function. Once I added it to the function in JavaScript it’s not working and the data is neither in the console and the UX:

<Each Items="{Rezept}">
 <Panel>	
   <DockPanel>
     <Panel Dock="Top" Background="#333" MaxWidth="300" Alignment="Left" Margin="0,20,0,0" Opacity="0.8">
     <Text  Value="{recipeName}" TextWrapping="Wrap" Alignment="TopLeft" Margin="10" Color="#FFFFFF" Font="Patua" FontSize="20"/>
    </Panel>
  </DockPanel>
<Each Items="{images}">
 <Image Url="http://XXX/{imageUrl}" Dock="Left" Margin="0,10,0,0"/>	
 </Each>
</Panel>			
</Each>

You are not doing any error checking. Add .catch(function(error) { } after your last .then.