Not all API results are being displayed by the Nextjs API function

I am facing an issue with rendering all the returns from the API in my Next.js application. The API, which is created in Strapi, is only displaying 1 out of the 3 possible returns. I am a beginner when it comes to using APIs and I suspect that the issue lies with the arrays "[0]" in the API request. However, if I remove this, nothing gets rendered. I've tried changing the index from 0 to 1 within the array, but it just moves to the next request instead of showing all the available data. Any assistance on why only one entry is being rendered would be highly appreciated!

API USAGE

// pages/categories/[category].js
import Link from 'next/link'
import {Text,VStack, Button, Icon, Heading, Alert, AlertIcon, AlertTitle, AlertDescription, Center } from '@chakra-ui/react'
import {FcExternal} from 'react-icons/fc'
import Moment from 'react-moment';


function Category({ categories }) {
  return (
    <VStack minH="500px">
    <Center>
        <Alert status="info">
          <AlertIcon />
          <AlertTitle>Please note:</AlertTitle>
          <AlertDescription>None of these papers are created or owned by the developer, they are created by the Department of Education Australia all rights go to them for these papers.</AlertDescription>
        </Alert>
      </Center>
        <Heading>{categories.name}</Heading>
        {categories.papers.map((cat) => {
          <div>
          <Text>Paper Uploaded at: {cat.created_at} </Text>
          <Text>Paper name: {cat.name}</Text>
          <Link href={`http://localhost:1337${cat.PDF_link}`}>
          <a target="_blank" rel="noopener noreferrer">
            <Button colorScheme="green" rightIcon={<Icon as={FcExternal}/>}>Open PDF</Button>
          </a>
          </Link>
          <Link href={`http://localhost:1337${cat.PDF_Answers_Link}`}>
          <a target="_blank" rel="noopener noreferrer">
            <Button colorScheme="green" rightIcon={<Icon as={FcExternal}/>}>Open Paper Answers</Button>
          </a>
          </Link>
          <Text>File Format: {cat.Media_Upload[0].ext}</Text>
          </div>
        })}
    </VStack>
  )
  }
  
  export async function getStaticPaths() {
    const res = await fetch('http://localhost:1337/Categories')
    const Categories = await res.json()
  
  
    const paths = Categories.map((category) => ({
      params: { category: category.id.toString() },
    }))

    return { paths, fallback: false }
  }
  

  export async function getStaticProps({ params }) {
    // params contains the post `id`.
    // If the route is like /posts/1, then params.id is 1
    const res = await fetch(`http://localhost:1337/Categories/${params.category}`)
    const categories = await res.json()
    console.log(categories)
  
    // Pass post data to the page via props
    return { props: { categories } }
  }

  export default Category
  
API Return
{
  id: 9,
  name: 'Entertainment Industry',
  Papers_Exist: true,
  web_link: 'categories/9',
  published_at: '2021-10-11T11:28:07.088Z',
  created_at: '2021-10-11T11:14:33.863Z',
  updated_at: '2021-10-11T11:28:08.221Z',
  papers: [
    {
      id: 4,
      name: 'Entertainment Industry Paper 2020',
      PDF_link: '/uploads/2020_hsc_vet_entertainment_18c5c978de.pdf',
      file_uploaded_at: '2021-10-11',
      PDF_Answers_Link: '/uploads/2020_hsc_entertainment_mg_5299ae9c24.pdf',
      published_at: '2021-10-11T11:28:14.016Z',
      created_at: '2021-10-11T11:27:46.534Z',
      updated_at: '2021-10-11T11:28:14.032Z',
      Media_Upload: [Array]
    },
    {
      id: 5,
      name: 'English Studies Paper 2019',
      PDF_link: '/uploads/2019_hsc_vet_entertainment_f2b48d77a0.pdf',
      file_uploaded_at: '2021-10-11',
      PDF_Answers_Link: '/uploads/2019_hsc_vet_entertainment_mg_fe47d01fdf.pdf',
      published_at: '2021-10-11T11:30:18.975Z',
      created_at: '2021-10-11T11:30:13.061Z',
      updated_at: '2021-10-11T11:30:18.989Z',
      Media_Upload: [Array]
    },
    {
      id: 6,
      name: 'English Studies Paper 2018',
      PDF_link: '/uploads/2018_hsc_vet_entertainment_acd7616cae.pdf',
      file_uploaded_at: null,
      PDF_Answers_Link: '/uploads/2018_hsc_vet_entertainment_mg_4a5d3e2660.pdf',
      published_at: '2021-10-11T11:31:42.294Z',
      created_at: '2021-10-11T11:31:40.155Z',
      updated_at: '2021-10-11T11:31:46.107Z',
      Media_Upload: [Array]
    }
  ]
}

https://i.stack.imgur.com/zCI80.png

getStaticProps $ getStaticPaths

export async function getStaticPaths() {
    const res = await fetch('http://localhost:1337/Categories')
    const Categories = await res.json()
  
  
    const paths = Categories.map((category) => ({
      params: { category: category.id.toString() },
    }))

    return { paths, fallback: false }
  }
  

  export async function getStaticProps({ params }) {
    // params contains the post `id`.
    // If the route is like /posts/1, then params.id is 1
    const res = await fetch(`http://localhost:1337/Categories/${params.category}`)
    const categories = await res.json()
    console.log(categories)
  
    // Pass post data to the page via props
    return { props: { categories } }
  }

Answer №1

If you want to render a list of elements instead of just one, consider using Array.map(). Here's an example based on your scenario:

<Heading>{categories.name}</Heading>

{categories.papers.map((el, index) => {
  return(
  <div>
    <Text>Paper Uploaded at: {el.created_at}</Text>
    <Text>Paper name: {el.name}</Text>
    <Link href={`http://localhost:1337${el.PDF_link}`}>
    <a target="_blank" rel="noopener noreferrer">
      <Button colorScheme="green" rightIcon={<Icon as={FcExternal}/>}>Open PDF</Button>
    </a>
    </Link>
    <Link href={`http://localhost:1337${el.PDF_Answers_Link}`}>
      <a target="_blank" rel="noopener noreferrer">
        <Button colorScheme="green" rightIcon={<Icon as={FcExternal}/>}>Open Paper Answers</Button>
      </a>
    </Link>
    <Text>File Format: {el.Media_Upload[0].ext}</Text>
  </div>
  )
})}
<Footer />

To learn more about Array.map(), check out the documentation here. P.S. You can apply the same method to render the Media_Upload array.

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

Every attempt to send data using ExpressJS results in a consistent 500 error code being returned

Currently, I am in the process of developing an API that involves web scraping. However, I seem to be facing a challenge that is perplexing me. The issue revolves around the GET request route provided below: const router = require("express").Router(); con ...

The API endpoint returns a 404 not found error on NextJS 14 in the production environment, while it functions correctly on the local

I am in the process of creating a small website using NEXT JS 14. On my website, there is a contact us page that I have been working on. In the GetInTouch.tsx file, I have the following code: <Formik initialValues={{ ...

JavaScript - Issue arises when evaluating the sine of complex numbers of large magnitudes

I have developed a unique sine calculator that can handle the evaluation of the sine of complex numbers by utilizing polar coordinates and computing part of the infinite series defining the sine function. The calculator performs smoothly when dealing wit ...

Adjust the text size of a label in material-ui

Hey everyone, I'm struggling with something here. I need to adjust the font size of the label that goes along with my textfield. So far, I've only been able to change the font size of the input itself and not the label. Here's the code for ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

Automatically fill in the Modal popup

Today, I encountered a challenge while trying to keep the current page in a jQuery data table. Clicking on the "Edit" link in a row would open a modal pop-up and fill in the controls. However, this action resulted in a postback that set the page back to pa ...

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

The Node.js Express server seems to be having trouble accessing static files

After successfully starting the express server, I encountered an issue when trying to load static files which resulted in an error message reading "Cannot GET /URL". The static files are located within a folder named "Login" and both the app.js and "Logi ...

Angular.js image slider display for viewing photos

Exploring the possibility of incorporating an open source widget to showcase images on a webpage, specifically leveraging angular.js. After conducting a search query on Google for "Angular.js photo carousel" or "angular.js photo viewer," I discovered only ...

Passing Node.js MySQL query results to the next function within an async.waterfall workflow

In my node.js code using express, I have set up a route to request data from a mysql database. My goal is to pass the returned JSON in tabular form to another function to restructure it into a hierarchy type JSON. I have individually tested the script to ...

Phaser 3 shows images as vibrant green squares

In my project, I have two scenes: Loading and Menu. In the loading scene, I load images with the intention of displaying them in the menu. Here is the code for the Loading scene: import { CTS } from './../CTS.js'; import { MenuScene } from &apo ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

In what format is the parameter accepted by the .getDay() method?

Here's the plan: I need to extract information from an input element with type set as date. This data will then be stored in a .json file and later parsed when the program is initiated. Subsequently, I aim to utilize the date.getDay() function to dete ...

Executing an AngularJS function through CasperJS is a common task that can

I am facing a challenge with testing a directive within a controller. The unit tests I am trying to write involve executing this code, which is triggered not by a click event but rather by a socket.io emit. Instead of attempting to mock socket.io, I am exp ...

What steps can we take to create a personalized PDF editor incorporating our unique edit functionalities using Vue.js?

Is it possible to create a PDF editor similar to MS Word using vuejs? How can I implement custom logic in the PDF editor with vuejs? For example, the features should include: Conditional replacement of text Adding tags to text within the PDF Changing the ...

Tips for obtaining the state of a local variable in a Vue method:

How do I access the state of a local variable within a method in Vue? I am looking to set a specific value for the dialog in order to open the popUp. After loading the data, my goal is to open the popUp by using this porting method. import { mapState, m ...

Prevent the selection of a dropdown option in AngularJS once it has already

var demoApp = angular.module('myApp', []); demoApp.controller('QaController', function($scope, $http) { $scope.loopData = [{}, {}]; $scope.questions = { model: null, availableOptions: [ {id: '1& ...

How to display JSON containing nested objects in AngularJS using the ng-repeat directive

Hey everyone, I have this JSON external file that I need help with: { "success":true, "errors":[ ], "objects":[ { "cod":"8211300", "descricao":"Serviços advocatícios" }, // more objects here... ] } In ...

Challenges when working with AJAX/jQuery in terms of fetching JSON data and setting dataType

I am currently facing a challenge with my practice of AJAX/jQuery coding. Despite my efforts to learn and improve, I find the concepts of jQuery and AJAX quite perplexing. Specifically, I am struggling to understand dataTypes and how to manage different ty ...

Transform the structure of an object using Ramda from its original form

Is it possible to transform an object by modifying and filtering it to create a different shape that is easier to work with after making an API request? I've been struggling to find elegant solutions that don't involve using path and prop for eve ...