Gab
Gab

Reputation: 2276

How to use window .fetch to load local json data (ES6)

I have a JSON object (agendaItemsJson) that I load using ES6 syntax (using json-loader via webpack). Using the following gives an error because fetch is trying to parse an URL and agendaItemsJson is an object.

So my question is how can I mimic this correctly so that I am able to use a promise and get agendaItemsJson to be my response.

'use strict';

import BaseService from './base-service';
import agendaItemsJson from '../json/agenda.json';

class _AgendaService extends BaseService {

    getAgenda() {
        // TODO: Will use API instead of the JSON here under.
        return this.fetch(agendaItemsJson)
            .then(response => response);
    }
...

Upvotes: 1

Views: 2612

Answers (2)

thitemple
thitemple

Reputation: 6059

If agendaItemsJson is the object you want to use as response using a promise you could do just this:

return Promise.resolve(agendaItemsJson);

This is shorter than creating a new Promise and it will resolve the value immediately.

And BTW, you wouldn't have to wait for a timeout to be executed.

Upvotes: 1

Thomas Maddocks
Thomas Maddocks

Reputation: 1385

Could you not just return a promise that is resolved with your agendaItemsJson? I.E use ES6 promises? You could even defer the response with setTimeout to simulate network delays.

getAgenda(){
    return new Promise(function(resolve){
        setTimeout(function(){
            resolve(agendaItemsJson);
        }, 1000);
    });
}

Upvotes: 2

Related Questions