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.
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 response.data. 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.