The error message "data.map is not a function" is thrown in the getStatic

I am currently working on a blog project using Strapi in conjunction with Next.js

My goal is to create dynamic pages by utilizing [id].js within the pages/posts/[id].js structure

However, I've encountered an issue while attempting to map through the Strapi API inside getStaticPaths(). The error message states that data.map is not defined

Important note: I am running Next.js version 12.0.8 and Strapi version 4.0.4

Below you can find the snippet of code causing the problem:

export async function getStaticPaths() {
  const postsRes = await axios.get("http://localhost:1337/api/posts?populate=image");
 
  const paths = postsRes.map((post) => {
    return { params: {id: post.id.toString()} }
  });

  // const paths = { params: {id: '1' } }
    
  return {
    paths,
    fallback: false
 
  }
 
}

To view the complete code for the [id].js page, click on this link - https://pastebin.com/SnzLirys

If you'd like to see a screenshot of the error, you can check it out here -

Answer №1

To reset the npm run dev, simply press ctrl + c to stop it and then start it again.

Answer №2

It seems that to successfully utilize axios within the specified function, you need to establish a context first. Alternatively, you could convert the axios response to JSON using json.stringify and then parse it using json.parse. Another option is to simply use the fetch method.

If you are working with the next API folder, avoid calling fetch or axios directly in this section. Instead, treat the query as if you were operating in a node environment.

export async function getStaticPaths() {
      const requestData = await fetch("url")
      const jsonData = await requestData.json()
      
      jsonData.map(item => console.log(item))
     
      const paths = jsonData.map((post) => {
        return { params: {id: post.id.toString()} }
      });
    
      // const paths = { params: {id: '1' } }
        
      return {
        paths,
        fallback: false
     
      }
     
    }

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

The AJAX Request has indicated that the entity provided is not in an accurate 'application/json' format. It seems to be missing or empty, leading to an error with a code of '400'

While attempting to create an AJAX request to submit users to an external API, I faced a problem that is hindering my progress. Since I'm more familiar with PHP than JS, I saw this as an opportunity to expand my knowledge in JavaScript. The approach ...

Utilizing JSON data from Google Maps Matrix with JavaScript

I am trying to fetch the real-time duration of a particular route on Google Maps through my JavaScript code. However, I seem to be stuck. Here's what I have written so far: $(document).ready(function Duration() { var d = new Date(); $.ajax({ ...

Troubleshooting Problems with File Upload Response in ASP.Net MVC Ajax.BeginForm

I have implemented a modal feature that allows users to upload a file. I am looking for a JSON response to indicate whether the upload was successful or not, and then display this information to the end user. Here is my current View: @model int <div ...

Is there a way to monitor and trigger a function in jQuery when a loaded PHP file is modified?

I am currently working on a dynamic dashboard that automatically updates every few seconds to display new information fetched from a PHP file. My goal is to trigger an alert only when there is a change in the data itself, rather than just a refresh. In ord ...

Minimize API Requests in Your AngularJS Application

Currently in the process of developing a straightforward web application that interacts with an API service. One issue I've encountered is the API call limit, which hinders the functionality if exceeded. How can I optimize my API calls to stay within ...

JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm ...

Exploring the Distinctions among JavaScript Objects

Currently facing a challenging problem and in search of an efficient solution. I have two Javascript Objects structured as {id:data, id:data, ..} If we focus solely on the Keys, they appear like this: B = ["1","2","3"] A = ["2","3","4"] My goal is ...

Manipulating arrays and troubleshooting Typescript errors in Vue JS

I am attempting to compare the elements in one list (list A) with another list (list B), and if there is a match, I want to change a property/field of the corresponding items in list B to a boolean value. Below is the code snippet: export default defineCo ...

What methods can be used to optimize web page designs for varying levels of user privilege?

When creating web pages for users with varying levels of access and privileges, what is the most effective approach to take? And also, how can we ensure the safety of our design? 1) Should we create separate pages for different user levels/privileges? Or ...

The text fields keep duplicating when the checkbox is unchecked

There are check boxes for Firstname, Lastname, and Email. Clicking on a checkbox should display the corresponding input type, and unchecking it should remove the input field. I am also attempting to retrieve the label of the selected checkbox without succ ...

When initiating Selenium RC, custom commands in the user-extensions.js file fail to load

Recently, I've been utilizing Selenium IDE to develop some tests. Within the IDE settings, I've specified a user-extensions.js file which is functioning as intended. Here's a snippet of its contents: Selenium.prototype.doactivateEnv = funct ...

Reveal a concealed div upon submitting an HTML form to display the resulting output

I have created an HTML form to gather information about a person's name and location. Once the user submits the form, I want the output to be displayed at the bottom of the page using PHP echo. My specific requirement is, To initially hide the outp ...

An unexpected error occurred: Angular is still not functioning correctly even though ng-route has been

Help! I'm encountering this dreaded error message: angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module usersApp due to: Error: [$injector:modulerr] Failed to instantiate module ngRoute due to: Error: [$injector:nomod] Modu ...

Implementing CSS styles according to user preferences. Switching between dark mode and light mode based on subscription

Is there a way to dynamically change CSS property values based on user interaction, such as toggling between dark mode and light mode? I am currently exploring the option of setting up a subscription to track these changes, but I want to know how I can act ...

Unable to showcase array JSON values on HTML using ng-model

Utilizing ngTagInput for autocomplete textbox and successfully receiving suggestions. To display the values of data-ng-model (named "list") I am using: {{list}} and it is showing correctly. However, when selecting "list1", the display appears as: [{"lis ...

What is the best approach to modify a user-inserted value on a webpage with both javascript and php?

In my PHP code, I have set up a variable that is displayed in an input field for the user. The user has the ability to change this value, however, when I try to retrieve the updated value using JavaScript, it doesn't seem to update. Instead, it remain ...

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

When JSON.stringify is used to convert an object to JSON, it will result in

I'm having difficulty creating a JSON object for transmission over the network. The particular array I'm dealing with looks like this in the Chrome debugger. event: Array[0] $$hashKey: "02Q" bolFromDB: 1 bolIndoor: null ...

JavaScript encountered an abrupt cessation of input, catching us off guard

Can someone please help me identify the issue with the JavaScript code below? I encountered an error message stating "Unexpected end of input", but upon reviewing the code, I couldn't find any apparent errors. All my statements seem to be properly ter ...