In the content of my website, there is a collection of objects named stories
that are displayed as an array. Additionally, I have a section where each individual story is showcased in detail.
I intend to enable users to click on any story link within the list and be directed to the detailed page for that specific story. Utilizing the _id
as a dynamic component of the URL is key, as illustrated below in the GraphQL code snippet.
The Graphql Query
export const listAllStories = () => {
const query = gql`
query StoryEntries($size: Int) {
storyEntries(_size: $size) {
data {
_id
_ts
name
premises{
data{
_id
content
}
}
createdAt
}
}
}
`
return graphQLClient
.request(query, { size: 999 })
.then(({ storyEntries: { data } }) => data)
}
Within My Pages API
export default async function handler(req, res) {
const handlers = {
GET: async () => {
const storyEntries = await listAllStories()
res.json(storyEntries)
},
}
if (!handlers[req.method]) {
return res.status(405).end()
}
await handlers[req.method]()
}
In The Overview Page For Each Story
const ENTRIES_PATH = '/api/entries/allStories'
const useEntriesFlow = ({ initialEntries }) => {
const { data: entries } = useSWR(ENTRIES_PATH, {
initialData: initialEntries,
})
const EntryItem = ({ entry }) => (
<>
{entries?.map((entry) => (
{entry.name}
<Link href="/story/[storyId]" as={`/story/${entry._id}`}>
<a>Go</a>
</Link>
))}
</>
)
export const getStaticProps = async () => ({
props: {
initialEntries: await listAllStories(),
},
revalidate: 1,
})
This implementation functions correctly and meets the requirements.
**On The Detailed Page For Each Individual Story [storyId].js
**
export default function Story({story}) {
const router = useRouter()
const storyId = router.query.storyId
return(
<>
<h5>hello {story._id}</h5>
</>
)
}
export const getStaticPaths = async () => {
const res = await fetch(`${server}/api/entries/allStories/`);
const { data } = await res.json();
const paths = data.map(story => {
return {
params: { id: story._id.toString() }
}
// Extracting the _id from each story
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const { storyId } = context.query;
const server = "http://localhost:3000";
const res = await fetch(`${server}/api/entries/allStories/${storyId}`);
console.log(res)
const { data } = await res.json();
return {
props: { story: data }
}
}
Error Message
TypeError: Cannot read properties of undefined (reading 'map')
Question
The main objective is to seamlessly navigate between the story list and individual story details using the unique _id associated with each story. Despite numerous attempts, I seem to be encountering issues or errors along the way.
Your assistance and guidance on this matter would be sincerely appreciated.
Edit After Receiving An Error: There appears to be difficulty in mapping the results obtained in the getStaticPaths method.