Next.js Static Paths Filtering

How can I retrieve only filtered paths from getStaticPaths?

This function currently returns all posts

export async function getStaticPaths() {
  const { data } = await axios.get(`${url}/category`, config);

 const paths = data.map((post) => {
    
      return {
        params: { postId: post.id },
      };
    
  });


  return {
    paths,
    fallback: false
  }
}

Here is my revised code

export async function getStaticPaths() {
  const { data } = await axios.get(`${url}/category`, config);

  const paths = data.filter((post) => {
     if (post.isActive) {
      return { params: { postId: post.id } }
     }
  })

  return {
    paths,
    fallback: false
  }
}

The error message received:

> Build error occurred
Error: Additional keys were returned from `getStaticPaths` in page "/product/[packageAlias]". URL Parameters intended for this dynamic route must be nested under the `params` key,

Answer №1

When using the <code>filter method, the object formatting will remain the same after filtration. To apply a map function after filtering, you can use the map method. Alternatively, you can combine both operations by using the flatMap method.

const paths = data.flatMap((post) => {
   return post.isActive ? [{ params: { postId: post.id } }] : [];
})

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 inconsistency of Selenium's StaleElementReferenceException error and the variability of pageload completion codes is causing issues with clicking on elements

Big shoutout to the amazing stackoverflow community for always providing assistance. Lately, I've been grappling with the frustrating "StaleElementReferenceException" issue and haven't found a universal solution yet. Some helpful members have rec ...

Using NextJs to create a permanent redirect from the www version of a site to the non

I have developed a website using Nextjs (version 12.1.4). To enhance the SEO of my site, I want to create a permanent redirect from the www version to the non-www version. Typically, this can be achieved easily using nginx or an .htaccess file with apache. ...

Strategies for resolving type issues in NextJs with Typescript

In my project using Next.js with TypeScript, I encountered an issue while trying to utilize the skipLibCheck = false property for enhanced checking. This additional check caused the build process to break, resulting in the following error: Error info - U ...

Received a dynamic server error while utilizing headers in my Next.js App Router

How can I resolve this error and still utilize both 'generateStaticParams()' and device detection? I don't want to sacrifice page load speed by using export const dynamic = 'force-dynamic'. The error message reads: "Dynamic server ...

Configuring lazy loaded modules with Angular 2 router

I am in the process of developing a service that utilizes router configuration to generate a map of routes based on components. Everything works smoothly except when dealing with lazy loaded module routes. I'm stuck on how to retrieve routes from a l ...

I am having difficulty viewing the div in HTML when using getStaticProps in Next.js - it does not appear when I view the page source in my browser

I am currently building a test SSR app with Next.js, React, and Apollo. However, I am finding it difficult to grasp how SSR actually works. After reading the documentation, I learned that in order to fetch important data during the initial SSR render, I n ...

Finding all parent IDs from a given child ID within a nested JSON structure that contains children can be achieved by recursively

function loadKendoTreeView() { if ($("#treeview").data("kendoTreeView") != null) { $("#treeview").data("kendoTreeView").destroy(); $("#treeview").empty(); } var jsonData = [{ "Id": "239297d8-5993-42c0-a6ca-38dac2d8bf9f", ...

Changing a transparent div with overlays into a visual representation of its underlying background

I am curious to know if it is feasible to carry out the operation mentioned, given that JavaScript doesn't currently have access to the contents of certain objects, such as a Flash video player. I have explored various screenshot plugins, but none of ...

Obtain the content enclosed by HTML tags

Looking to extract text between html tags? Imagine having a list of cities in California, each within paragraph tags. Can you retrieve only the text inside the paragraph tags? <div class="cities"> <div><p>Los Angeles</p><h5 ...

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

Utilizing Subdirectories in a Command Manager

My goal is to organize my commands into sub folders, but for some reason my bot is not recognizing the commands inside those folders. Strangely, no error message is being displayed. const fs = require('node:fs'); const Discord = require('dis ...

Having trouble with accessing an element that contains both onclick and text attributes in Selenium Webdriver?

The HTML code I'm dealing with includes this element: <a style="text-decoration:none; font-weight:normal;" href="javascript:void(0);" onclick="CreateNewServiceItemApproved();"> <img src="icons/ui/addnew.png"> <span style="color:# ...

The carousel spun around, each section moving to the side on its own

One issue I'm facing is that on my page, I have multiple carousel rows. However, when I click on the "next" or "prev" button to navigate through the items in the carousel, it affects all carousels instead of just the one I clicked on. I've attem ...

"An error occurred while trying to access the data for a new user on the snapshot object while navigating to the screen. It seems that the object is

When I navigate to the screen, I use componentDidMount to trigger fetchNewUser which is meant to detect a new user and update it if necessary. However, I encounter an issue where on initial navigation to the screen, it returns undefined is not an object ...

What is the process for obtaining the URL type for Higher Order Components in NextJS?

When building a component with a Link, I am struggling to properly define the type for the href prop. import React from "react; import Link, { LinkProps } from "next/link"; type MyComponentProps = { href: Pick<LinkProps, "href&quo ...

Is it possible to redirect a URL with a readyState of 4?

Is it possible to redirect to a page when the readyState is equal to 4? //load the send form if (sendRequest) { sendRequest.open("POST", urlRequest, true); sendRequest.setRequestHeader("Content-Type", "application/x-www-form-urlenc ...

Steps for eliminating the chat value from an array tab in React

tabs: [ '/home', '/about', '/chat' ]; <ResponsiveNav ppearance="subtle" justified removable moreText={<Icon icon="more" />} moreProps={{ noCar ...

The function WebForm_DoCallback is not recognized

Encountering an error where WebForm_DoCallback is undefined. UPDATE WebForm_DoCallback("AccountPageControl1", "FileSave~" + fileName, CVFileSavedServerResponse, null, null, true); function CVFileSavedServerResponse(param, context) { } Why isn't ...

Retrieve the JSON element from a Backbone model by its unique identifier

I'm diving into Backbone for the first time and I'm facing difficulties making it work smoothly with a JSON data file. Here's how my model looks: window.Test = Backbone.Model.extend({ defaults: { id: null, name: null, }, url: f ...

How can I represent non-ASCII characters in Java Script using encoding?

Imagine if ch = á the desired result is = \u00e1 however the current output = %E1 when escape(ch) is used and current output = %C3%A1 when encodeURIComponent(ch) is used I am working with an API that supports Unicode characters. ...