I am attempting to learn Next.js by expanding upon Brad Traversy's Next.js code. There is already one API route that returns a JSON object with all articles.
I am attempting to add "category" and "subcategory" attributes to the items in the data and create a series of routes that look like root.com/category/[category]/subcategory/[subcategory], but they all pull from the same dataset. To do this, I've tried to slugs that look like this under the API folder:
> category
>> index.js
>> [category].js
> subcategory
>> index.js
>> [subcategory].js
Each of the index.js files looks like this:
import { items } from '../../../data'
export default function handler({ query: { category } }, res) {
const filtered = items.filter((item) => item.category === category)
res.status(200).json(filtered[0])
}
The [slug].js files look like this:
import { items } from '../../../data'
export default function handler({ query: { category } }, res) {
const filtered = items.filter((item) => item.category === category)
res.status(200).json(filtered[0])
}
(so the same, I understand this might be redundant but I am throwing spaghetti at the wall). The intent of this is to only pull items where the category or subcategory matches the query.
In the pages, I have a structure like this (if this could be collapsed into one, that'd be great):
> category
>> [category]
>>> index.js
> subcategory
>> [subcategory]
>>> index.js
Where each of the index.js files looks like this:
const category = ({ items }) => {
return (
<>
<Meta title={items.category} description={items.category} />
<div>
<ItemList items={items}/>
</div>
<Link href='/'>Go Back</Link>
</>
)
}
export const getStaticProps = async (context) => {
const res = await fetch(`${server}/api/category/${context.params.category}`)
const item = await res.json()
return {
props: {
items,
},
}
}
export const getStaticPaths = async () => {
const res = await fetch(`${server}/api/items`)
const items = await res.json()
const categories = items.map((item) => item.category)
const paths = categories.map((category) => ({ params: { category: category.toString() } }))
return {
paths,
fallback: false,
}
}
export default category
However, the list of items is always the same on the front end. Could someone please help me understand what is happening, or a better approach to nested routing in Next?