Svelte: Guide for getting json data to components?

Created on 17 Mar 2018  路  5Comments  路  Source: sveltejs/svelte

I know this subject has been a bit of a moving target, but most apps these days need some external data - and are constantly updating that data as the user goes through the app. The docs have bits and pieces about how to fetch json, and how to use it in a component, or fetch from a component - but after trying most of the examples I could find - I still don't have a clear idea of how to just grab some json from an online source, and use it to populate a simple table or something. While async seems cool - even just regular sync would be fine - I could just use some really clear example show to get this done. Right now I've tried this here (sorry I can't see how to share a REPL!). In my case I am only asking for ways to get data client side, as my apps all serve on Netlify.

App.html

<Showcase dataUrl='https://raw.githubusercontent.com/mspanish/playground/master/kwippe_icons'/>

<script>
    import Showcase from './Showcase.html';

    export default {
        components: {
            Showcase
        }
    };
</script>

Showcase.html

{{#await showcaseData}}
    <p>pending</p>
{{then result}}
    <p>{{result}}</p>
{{catch err}}
    <p>oops! {{err.message}}</p>
{{/await}}

<script> 
    export default {
        computed: {
            showcaseData: showcaseUrl => {
                return new Promise(fulfil => {
                    setTimeout(() => {
                        fulfil('things and stuff');
                    }, 1000);
                });
            }
        }
    };
</script>

I don't necessarily need the async stuff - and would be happy with just fetch and show data too - but the more clear examples on this stuff the better :)

help wanted

Most helpful comment

Loading JSON in an oncreate hook, as per the CodeSandbox demo, is a very common way to go. In modern browsers, you don't need to use a library like axios, you can just use the built-in fetch:

oncreate() {
  var urly = 'https://raw.githubusercontent.com/mspanish/playground/master/kwippe_icons'      
  fetch(urly)
    .then(res => res.json())
    .then(data => {
      // console.log(data)
      this.set({icons: data})
    });
}

(There's also a fetch polyfill if you need to support old browsers, and a smaller version that satisfies 90% of use cases.)

In Sapper, you also have the preload hook, which delays rendering the page until the data is ready (avoiding any brief flashes where no content is displayed):

preload() {
  var urly = 'https://raw.githubusercontent.com/mspanish/playground/master/kwippe_icons'      
  return fetch(urly) // <!-- note that we're *returning* the promise this time
    .then(res => res.json())
    .then(data => {
      // console.log(data)
      return {icons: data}; // <!-- and we're returning the result, rather than this.set(...)
    });
}

All 5 comments

I did finally find a really nice example of getting external JSON data into a Svelte component, albeit with axios! codesandbox.io demo here

Loading JSON in an oncreate hook, as per the CodeSandbox demo, is a very common way to go. In modern browsers, you don't need to use a library like axios, you can just use the built-in fetch:

oncreate() {
  var urly = 'https://raw.githubusercontent.com/mspanish/playground/master/kwippe_icons'      
  fetch(urly)
    .then(res => res.json())
    .then(data => {
      // console.log(data)
      this.set({icons: data})
    });
}

(There's also a fetch polyfill if you need to support old browsers, and a smaller version that satisfies 90% of use cases.)

In Sapper, you also have the preload hook, which delays rendering the page until the data is ready (avoiding any brief flashes where no content is displayed):

preload() {
  var urly = 'https://raw.githubusercontent.com/mspanish/playground/master/kwippe_icons'      
  return fetch(urly) // <!-- note that we're *returning* the promise this time
    .then(res => res.json())
    .then(data => {
      // console.log(data)
      return {icons: data}; // <!-- and we're returning the result, rather than this.set(...)
    });
}

awesome I didn't think I needed to use Axios - thanks very much for these simple examples.

Moving to a framework like Svelte is pretty big mental shift for folks like me who have been dealing with stuff like Backbone/jQuery/Templates for the last 5 years - the way you have to import stuff in your dev step rather than throwing in a script tag later, make sure it's compatible, etc, makes a lot of things less obvious. But in the end the result will be terrific - I'm already amazed at what I've been able to do with far less code that I've previously used.

Anyone with a good guide on how to manage data, if I have several components and need them to share the data.

That is my confusing part, Since i have several endpoints

this is a very old issue, dont ask here. try the discord instead.

today, you should probably use sapper and do multiple fetches to share data.

Was this page helpful?
3 / 5 - 1 ratings

Related issues

1u0n picture 1u0n  路  3Comments

robnagler picture robnagler  路  3Comments

Rich-Harris picture Rich-Harris  路  3Comments

rob-balfre picture rob-balfre  路  3Comments

mmjmanders picture mmjmanders  路  3Comments