How to retrieve values from a nested array in a Next.js application

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!

Answer №1

Looking at the data provided, it seems like there is an issue with trying to map over courses as if it were an array, when in fact it is an object. Inside this object, there is a property called courseFeed which is actually an array. To properly iterate over it, you should do something like this:

<ul>
  {courses.courseFeed.map((course) => ( 
  {/* More stuff */}
</ul>

An Update

Based on your comments, it appears that you are encountering an error message stating

Error: Objects are not valid as a React child
after applying the suggested fix above.

This error indicates that course.creator cannot be rendered directly since it is an object and not a compatible type for React. As seen in the log message you shared, the structure of this object includes keys such as {__typename, id, lastName}. If you intend to display the last name of the creator, you would need to adjust the code accordingly:

<p>{course.creator.lastName}</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error thrown: Upon attempting to reopen the modalbox after closing it, an uncaught TypeError is encountered, indicating that the function $(...).load

An unexpected error occurred: $(...).load(...).modal is not functioning properly After closing a modal, I encountered this error in the console when attempting to reopen it. Strangely, it seems to work intermittently for a few times before throwing this e ...

The Next.js build output continues to display the Pages Router even after transitioning to the App Router

After migrating all the routes on my project from pages router to app router, I no longer have a pages folder. However, the build output is still displaying the pages router's 404 route. View Build Output Route (pages) S ...

Choose options with identical titles

If you click on the button to add more selects with the same name, I want to replace them so that you can access them in a PHP array. document.querySelector('#add').onclick = function () { var thespan = document.createElement('span&apos ...

Fade out the div element when clicked

For my game project, I needed a way to make a div fade out after an onclick event. However, the issue I encountered was that after fading out, the div would reappear. Ideally, I wanted it to simply disappear without any sort of fade effect. Below is the co ...

Resetting the form and validation in AngularJS post form submission

I need help resetting a form and all validation messages after submission. Check out my code on plunker: http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview Here is the code snippet: Controller: app.controller('MainCtrl', function($scope) { ...

Error encountered when using the module export in Node.js

I have a file named db.js which contains the following code: var mysql = require('mysql2'); var mysqlModel = require('mysql-model'); var appModel = mysqlModel.createConnection({ host : 'localhost', us ...

Perform a Selenium action to click on each individual HTML 'a' tag on

I am attempting to automate clicking on all the "a" tags within a website using Selenium in Python. However, I found that all the "a" tags I want to click have the same structure as shown in the code snippet below. I tried clicking them by their class si ...

MongoDB date query with $gte and $le operators mm/dd/yy

Apologies in advance for any language errors. The problem I am dealing with involves a column in the database called "Date" inside the "startOn" Object. This setup creates a structure like "startOn.Date" with data format as yyyy/dd/mm. For example, if we ...

What is causing the React text component to fail to show changes made to my array state?

I am currently in the process of learning React Native. I have been working on an app and encountered an issue while attempting to update individual elements within an array. Here is an example of the code: function MyApp() { const [array, setArray] = ...

Challenges encountered when setting up a containerized application using Next.js, Flask, and PostgreSQL

Challenge: I've been encountering difficulties in containerizing my application that includes a Next.js frontend, Flask backend, and PostgreSQL database. The primary issue I'm facing currently is the incorrect loading of my PostgreSQL schema. St ...

Is there a way to access the userID in the React.js front-end?

As I work on completing my Full Stack Web app with JWT token authentication based on roles, I find myself facing challenges with the front-end development. Specifically, I am unsure of the best practice for retrieving the UserID in the front-end to facil ...

Deploying React application to Heroku resulted in an Application Error even though there were no errors during the build

I'm facing some issues while deploying my React app on Heroku. Even though the app compiles and builds successfully on both my local server and Heroku, it still shows an error. I've added https://github.com/mars/create-react-app-buildpack.git to ...

Information within specified dates shows all leaders

Looking to filter data based on Start Date, End Date, and HeadName. The current search query successfully filters between dates but does not properly filter the HeadName column, displaying all results instead. Sno HeadName Date Amount BillNo BillD ...

D3 group of legendary elements

Is there a way to group both the circle and text elements for each legend item together? I'm currently facing a challenge with the enter/exit methods. While I can create the groups (g), I'm unable to append the text and circle elements. li.sel ...

Implementing conditional dropdown menus with CodeIgniter

Explore the District Master Table: Dive into the District table: District Master District I need assistance with a form page that includes a Category dropdown. The district table stores district codes and category names. I want to display district names ...

Efficiently combining two arrays in PHP without any duplicate values

After analyzing two tables, I have the following arrays: $array1 = (2, 7, 9, 15); $array2 = (3, 7, 10, 15); I am looking to combine these tables into a single array without any duplicate values. The desired result should be: $result = (2, 7, 9, 15, 3, 1 ...

Error in JScript encountered during the downgrade to .NET Framework 2.0

Working on a Web Application project has brought about some challenges for me. Originally created in .NET 3.5, I recently found out that it has to be converted to .NET 2.0 (sigh). This transition not only caused issues with the LINQ functionalities but als ...

NextJS 13 - 404 Looks like this page has gone missing. Application router in development mode

I am currently facing a problem with my project in NextJS 13 using the App Router. Despite the layout.tsx elements functioning properly, I am getting a 404: Not Found Error on both the index page and subsequent router pages. I have included my next config, ...

Automatically generate nested object properties in VueJS for streamlining code structure

Understanding the Issue I have created a custom system to monitor specific "store" properties from a JSON in a NoSQL database. The structure is fairly straightforward, with nested objects that are necessary for various reasons. The data format resembles ...

Remove an image that has been selected while uploading multiple images using AngularJS

If I want to delete a specific image from multiple uploads by clicking on the image in AngularJS, how can I achieve this? Each uploaded image has an associated textbox. When the delete icon on the image is clicked, both the image and the corresponding text ...