Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Load Data from APIs with Nuxt and Vuex


    Before each page loads, Nuxt supports pre-fetching data to render what you need on the server. This lesson walks you through using Nuxt's fetch to load data then save it in the Vuex store.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    To load some todos into our application let's first set up an API. Install a library called Now, and the awesome thing about Now is that it actually lets you deploy projects straight off of GitHub and this project at John Lindquist's Todo API.

    When you type "Now John Lindquist Todo's API," will find it on GitHub, deploy it, and then give you a URL which when I visit this URL will have a server up and running where, if I request todos, it'll give me back an array of todos.

    With this link here I can get and post and delete and patch and anything I want to these todos. To load these in I'm going to add a library called Axios, which gives me a nice clean way of working with remote data. With that installed I'll start up my dev server again, say yarn-run dev.

    Each page or each component, so for my index view, in my code here, a fetch will be invoked when the page is loaded. Fetch for me is going to be a function where I can Axios get that array of data. I'm going to use the async Await syntax to make this a nice, clean call to this promise. That way I don't have to .then everything.

    This will be a response and then when I get that response back, fetch also passes in an object with a store on it. I can say store, commit, and I'll say innit, which is going to be a function on my mutations. Innit, which will take a state and an array of todos, and simply say the state.todos is that new array of todos.

    Then back in here I'm going to pass in the Obviously this is telling me Axios is not defined. That's because I forgot to import Axios from Axios. Now when I save, and often when you get errors it breaks that hot reload connection, so I just refresh.

    You can see we now have eat, sleep, code. This is now coming from here, so I can go ahead and delete these todos. You'll notice that it's still loading in eat, sleep, and code.