⚠️ This lesson is retired and might contain outdated information.

Load Data into the Vuex Store in Nuxt

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 2 months ago

With axios installed, you can load data and store it into your Vuex store on the server-side before your app even renders. This lesson walks you through using axios to load data in a Nuxt news app and adding it to the store to display on any page.

We'll switch this over to the Hacker News API, which means in our store now, we can load topstories.json. This will give me back a list of IDs linking to the top stories we want to load. I'll go ahead and find and replace users to IDs, and set IDs to set IDs.

You can see now it's IDs everywhere, and this can just be an empty array. Then in my index page, I'll just show that this is a set of IDs, and drop my IDs in here. I'll run this, and you can see this is a giant array of IDs.

I'll use these IDs. First, I just want to get 10 of them. 10 IDs is IDs slice 0, 10. Then I'll turn these 10 IDs into items promises, because Hacker News refers to these as items. I'll just say 10IDs.mapID is mapped to an Axios getItem/the-ID.json.

Then to load all of these promises, I can await promise.allItemsPromises. I'll just call this items responses. Then we only want the data, so we'll call just just items. We'll take the items responses, and map the response to response.data.

Now, instead of set IDs, we can just say commit set items, pass in the items, scroll up to here. We'll create a mutation called set items. This is state and items, and state.items equals items. Then our state will just have an initial items of an empty array.

Now, to show our items in our index, we'll say please show the items. The users are gone completely, and in these IDs, I'll just say items. Now, you can see an array with a ton of objects in it, and what we want is the title property.

I'll take this off, because I don't need a large font anymore. Delete this line. I'll say for item in items, the key can be the item ID. Then we'll show the item.title. Hit save here, and then you'll see the item titles from Hacker News displaying in our index page.

Then just for some quick formatting, I'll use the Tachyons classes of list to get rid of the bullets, and padding all two to give us some nice padding, just to make that look a little cleaner.

Eleonora Lester
Eleonora Lester
~ 5 years ago

The correct axios get for json items from hackernews:

axios.get(`item/${id}.json?print=pretty`)

From https://github.com/HackerNews/API

Markdown supported.
Become a member to join the discussionEnroll Today