A guide on utilizing getStaticProps to map a collection obtained from Strapi within a Next.js component

I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be applied to arrays, while we are fetching an object from Strapi. How can I work around this issue? Additionally, in the tutorial at the 30-minute mark (link), the instructor uses the .map function even though "posts" is an object. How does that function correctly?

export default function Home({ posts }) {
  return (
    <div>
      {posts &&
        posts.map((post) => (
          <div key={post.id}>
            <p>{post.Title}</p>
          </div>
        ))}
    </div>
  );
}

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/api/posts");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

UPDATE: I managed to solve the problem by writing the following code:

export default function Home({ posts }) {
  return (
    <div>    
      {posts &&
        posts.data.map((post) => (
          <div key={post.attributes.id}>
            <p>{post.attributes.Title}</p>
            <p>hello there</p>
          </div>
        ))}
    </div>
  );
}

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/api/posts");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

The JSON data I wanted to access was located under the 'data' and 'attributes' properties.

Answer №1

It seems like you may be accessing the incorrect endpoint (depending on the version of Strapi you are using):

For Strapi v3

If you are following a tutorial for versions below v4, the correct endpoint would be http://localhost:1337/posts, not http://localhost:1337/api/posts as shown in the video.

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/posts");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

Accessing http://localhost:1337/api/posts might result in an error string or object being returned.

For Strapi v4

However, if you are using Strapi v4, the response is structured in JSON:API format, with a data object containing the array. Refer to .

In this scenario, you can iterate through the array within the data object:


    {posts &&
        posts.data.map((post) => (
          <div key={post.id}>
            <p>{post.Title}</p>
          </div>
        ))}

If you encounter such issues, consider checking the Network tab in your browser to inspect the XHR request response, or log the result to troubleshoot and find a resolution.

Answer №2

During the tutorial video at this specific point, an array is showcased containing objects. The method map() is utilized to iterate through each item in the array, with the object being returned as the variable post.

Understanding why Strapi does not return an array requires inspecting what is actually retrieved by the posts. According to the API documentation, it seems that the array could potentially be nested under the key data. Additionally, if only one entry is fetched, it may not be within an array (in such cases, you can manually add brackets around it or avoid using map() altogether.

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

Dealing with extended render times in React applications

Currently, I'm working with a limited set of 100 documents per page and utilizing a wrapper component for certain conditional actions. const onClickCheckbox = (order: OrderProps) => { const _ordersToExport = [...ordersToExport]; const ind ...

Remove hidden data upon moving cursor over table rows after a delay

Hey there! I'm in need of a little assistance, so I hope you can lend me a hand. Here's the scenario: Within my category table, there are numerous rows, each containing a hidden textbox with an empty value and a unique ID. As users navigate t ...

Conceal a button using an AJAX POST request

I'm encountering an issue with my Ajax post where I am trying to disable the button used to submit data. I've reviewed my code and it seems accurate, but the button is not getting disabled. I attempted using $("#refreshButton").attr("disabled", t ...

Encountering difficulty extracting information from JSON file within AngularJS factory

I am struggling with a Json file named discover.json located at json-files/discover.json {"data": [ {"username": "aky123", "name": "ajay"}, {"username": "sky123", "name": "sanjay"} ]} Below is my factory setup: var myAppServices=a ...

Problem with Azure Table JavaScript Solution

When attempting to utilize JavaScript to access Azure Storage Tables, I encountered an error that reads: "Error getting status from the table: TypeError: tableServiceClient.getTableClient is not a function." Despite finding multiple successful examples onl ...

Dropzone failing to verify the maximum file limit

I am currently using dropzone to upload files on my website. I have limited the number of files that can be uploaded to a maximum of six. The code works perfectly when uploading one image at a time, but if I select more than six images by holding down the ...

Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player. This is how my code currently looks: const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: &apo ...

Angular - ui-router states are not being detected

I'm currently working on a Spring and Angular JS web application project. The structure of the project is as follows:https://i.sstatic.net/xgB4o.png app.state.js (function() { 'use strict'; angular .module('ftnApp') .con ...

The compatibility issue arises when using Nextjs Middleware with Next Auth V5 on Amplify, prompting error messages such as "Server configuration problem" and "Host must be trusted"

System: OS: macOS 14.3.1 CPU: (10) arm64 Apple M1 Pro Memory: 174.97 MB / 16.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 18.17.1 - ~/.nvm/versions/node/v18.17.1/bin/node Yarn: 1.22.19 - /usr/local/bin/yarn npm: 10.2.4 - ~/.nvm/versions/node/v18.17.1/bin/np ...

Optimal approach for incorporating controller As with UI Router

Currently working on a small search application using AngularJS and Elasticsearch. I am in the process of transitioning the app from using $scope to controller As syntax. I have implemented UI Router for managing routes/states. I have been attempting to us ...

What causes the delay in loading certain CSS and JS files?

My ASP.NET MVC5 application hosted on an IIS Server has a slow-loading login page, especially after clearing the browser history. The Developer Tools Network field indicates a problem with loading page contents such as css and js files. Can you provide gui ...

Fill the dropdown menu with JSON keys

My challenge involves working with an array containing objects, which are sent to the client via a node.js server integrated with mongodb. I need to extract all keys/fields from the object (such as name, surname, telephone) without their values (for exampl ...

Checking a bcrypt-encrypted password in an Express application

I am encountering an issue with my login password verification code. Even when the correct password is entered, it is not being validated properly. Can anyone provide assistance with this problem? login(req, res) { const { email, pass } = req.body; ...

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

I encountered an issue while trying to use jshint with a simple hello world script, receiving the error message: "line 0, col 0, Bad option: 'script'."

This is a basic introduction to my coding journey. function greet() { return 'Hello world'; } Here is the jshint setup I am using: { "browser": true, "browserify": true, "devel": true, "script" ...

PHP - Offline/Online Status Polling Protocol Guide for Beginners

I am in search of a solution to track the online and offline status of users on my website. My site is a single page with no clickable links, so users may leave their tabs open for long periods without interaction. It is not essential to pinpoint the exact ...

Elevate Your Nextjs React Application with Doctorize

I have created an SSR Next.js application using React. I am currently facing issues while trying to launch the application with Docker. I have set up a Dockerfile and docker-compose, but I seem to be stuck at making the app run successfully. Below is my D ...

The Typescript counterpart to PropTypes.oneOf, utilizing a pre-existing variable

While I know this question has been addressed on Stack Overflow here, I still find myself struggling with a similar issue in my TypeScript project. Currently, I am in the process of converting a JavaScript project to Typescript. Within one of my React com ...

Having difficulty locating audio files within a Next.js project

I am facing challenges when trying to import my audio files into a redux slice. Currently, I am attempting to retrieve my audio files from the app > public > audio directory. I have made efforts to access my audio files through 2 different director ...

What could be the reason for my image not loading properly in Vue.js 3?

I'm struggling to load an image using a relative path and value binding with v-for in my template code. Despite following the correct syntax, the website is displaying an error indicating that it can't retrieve the image. Here's a snippet of ...