The data we load depends on which URL we are on. If we're at the index or root, we'll load top stories. If we're at /new we'll load news stories and so on, across out URLs. We'll set that up by going over to our index view page and essentially cutting out everything and adding that into a component.
In our components folder, I'll create a file called items.view and paste everything in there. Back in my index.view, I can say template then script. In my script tag, I'll import items from /components items.view.
I'll add it to my components. Then I can use it inside of my template. Now, when I run this, I'll have the exact same output. What this allows us to do is load the store up, based on the page we load. In our index.view I can say fetch. This is a hook or a method that's called to prep the store with data.
Essentially what I'll do is grab the store off of the context and then dispatch an action. We'll call this load-items. Uppercase that. The payload I want to send along is top stories.Jason. I also need to note here that, because this is asynchronous, we'll need to async/await this, so that the page doesn't display before that data changes.
Then we can hop over to our store, change next-server in it to load-items. Again, we'll uppercase this. As of right now it still behaves the same. The index page loads. It loads in the items component. We display the items component here. We load the items data into the store using store.dispatch(load-items), which triggers our load items.
Now, we can extract this top stories.Jason. We'll just call this data URL and say this is the data URL, because, in these actions, this first one is the context. The second one is the payload. When I save, we'll get the same thing.
Now, I created the index to load top stories. We can work on new, which essentially is just copy/paste. Rename this to new. Rename this to news stories It's saved. Now, when I navigate to /new, you'll see we get news stories.
When I navigate to index, we're back at the index. You can tell these apart, let's wrap these. Drop an H1 in here. We'll just call it top. In my new we can wrap the items. Drop another H1 in. Call this new. That took care of new.
To build ask, we'll do the same thing. Copy/paste/new. Rename this to ask. This is ask. This is now ask stories. Now, we have /ask. Back to the home page. I'm also going to quickly add a show, and a jobs, and fast forward through that process.
Now, we have /show/jobs/ask the index. It looks like /new is giving us an error. One of these is coming back as null in my responses. Let's just handle that temporarily as "real items". We'll say "items map".
Then, if the item is null, we can return an object with the title of failed to load and an ID of zero. If it properly loaded, we'll just return the item. My formatter made it look like this, which is fine. Change this to real items. Hit save. See what happens here. It looks like this one was the one that failed to load.