The hikr example with use of api fetch

I have read the hikr-tutorial where the hikes-data is hardcoded. How would the Backend.js file look like if the hiker-data came from an api like http://api.hikr.com/get?

And what about the Context.js? Any changes there? As I understand you should not need to change the Context-file, only the Backend-file?

There are examples of fetch, but not like the hikr-tutorials use of Promise.

This is the example from hikr Backend.js:

var hikes = [
{
	id: 0,
	name: "Tricky Trails",
	location: "Lakebed, Utah",
	distance: 10.4,
	rating: 4,
	comments: "This hike was nice and hike-like. Glad I didn't bring a bike."
},

function getHikes() {

return new Promise(function(resolve, reject) {
	setTimeout(function() {
		resolve(hikes);
	}, 0);
})

}

Hey!

You could write something like this:

var Observable = require("FuseJS/Observable");
var data = Observable();

function execute(method) {
  var p = new Promise(function(resolve, reject) {
    var url = "http://api.hikr.com/";
    fetch(url)
      .then(function(response) {
        return response.json();
      })
      .then(function(responseObject) {
        resolve(responseObject);
      })
      .catch(function(err) {
        reject(err.message);
      });
  });
  return p;
}

function getData() {
  execute("get?")
    .then(function(x) {
	data.replaceAll(x);
    }).catch(function(e) {
	console.log(e);
    });
}

module.exports = {
	data: data
}

Hope this helps.

Thanks! After some studying and experimenting with a real api (get some articles) I came up with something like this.

In Backend.js:

function getHikes() {
	return new Promise(function(resolve, reject) {
		fetch("http://api.hikes.com")
		.then(function(result){
			var hikes = result.json();
			resolve(hikes);
		})
		.catch(function(error) {
			reject(error);
		})
		
	});
};

module.exports = {
getHikes: getHikes
};

In Context.js:

var Observable = require("FuseJS/Observable");
var Backend = require("./Backend");

var hikes = Observable();
		
	Backend.getHikes()
	.then(function(newHikes) {
		hikes.replaceAll(newHikes);
	})
	.catch(function(error) {
		console.log("Couldn't get hikes: " + error);
	});		

module.exports = {
	hikes: hikes
};