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

    Load Data from APIs with Nuxt and Vuex

    John LindquistJohn Lindquist

    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 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


    00:00 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.

    00:17 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.

    00:35 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.

    00:54 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.

    01:20 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.

    01:46 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.

    02:04 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.