I am diving into the world of nextjs and apollo for the first time, and I am currently facing a challenge with using .map
to loop through database results.
Below is the code for my component:
import { gql, useQuery } from "@apollo/client"
import Link from "next/link"
import ErrorMessage from "../layout/ErrorMessage"
export const ALL_COURSES_QUERY = gql`
query getCourses($limit: Int, $field: String!, $order: Order!) {
courses(limit: $limit, sort: { field: $field, order: $order }) {
courseFeed {
id
title
videos {
title
}
creator {
id
lastName
}
sections {
title
}
ratings {
id
}
deletedAt
}
pageInfoCourse {
nextPageCursor
hasNextPage
}
}
}
`
export const allCoursesQueryVars = {
limit: 10,
field: "title",
order: "ASC",
}
export default function CourseList() {
const { loading, error, data } = useQuery(ALL_COURSES_QUERY, {
variables: allCoursesQueryVars,
})
if (error) return <ErrorMessage message="Error loading courses." />
const { courses } = data
console.log(courses) // see output below
return (
<section>
<ul>
{courses.map((course) => (
<li key={course.id}>
<Link
href={{
pathname: "/courses/[slug]",
query: { slug: course.slug },
}}>
<a>{course.title}</a>
</Link>
<p>{course.creator}</p>
</li>
))}
</ul>
</section>
)
}
console output
{
__typename: 'CourseFeed',
courseFeed: [
{
__typename: 'Course',
id: '607c1f1201509f26b866cbba',
title: 'Kurs Eins',
videos: [Array],
creator: [Object],
sections: [Array],
ratings: [Array],
deletedAt: null
}
],
pageInfoCourse: {
__typename: 'PageInfoCourse',
nextPageCursor: null,
hasNextPage: false
}
}
Error Message
TypeError: courses.map is not a function
I need assistance in iterating over the courseFeed
array to properly utilize the course objects within my page. Any help or guidance would be greatly appreciated!