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

Leverage JSON data from an API within JavaScript, sourced and accessed through PHP

I'm seeking advice on using JSON data (loaded in PHP) with JavaScript. I am currently retrieving the JSON from an API, but someone suggested that using curl would be more efficient? I've attempted to research curl, but haven't found exactly ...

Encountering an issue in a Vue console where the $ref is returning null and prompting an error message

It's puzzling why I keep encountering a console error in Vue that says "cannot read null of a $ref". Despite having the correct HTML template and adding logic to the script tag as needed, I'm still facing this issue - Cannot read properties of nu ...

The process of obtaining points through accurate responses using form inputs

My task is to create a unique quiz consisting of 10 questions. Half of the questions are multiple choice, which require radio inputs, while the other half are written answers that need text inputs. To ensure accuracy and provide a scoring system, I came ac ...

What's causing these divs to be misaligned in various directions?

I am currently working with a front-end framework based on flexbox called Material-UI, and I have noticed that the layout of certain components, particularly the quantity control elements, appears to be different even though they all share the same styling ...

Using JavaScript to call a PHP file as the source file

I'm curious about the scenario where a .php file is called as a javascript. What does this signify and in what situations would it be necessary to use such an approach? Example: <head> <script src="dir/myphpfile.php" type="text/javascript" ...

What is the proper usage of a jwt token?

I'm completely new to this and I've dedicated all my time to figuring out how to create a mechanism for generating JWT tokens. These tokens are necessary for identifying the 'signed in' status of users. I opted for FastAPI, and after s ...

Implementing individual NGRX Selectors for each child component to enable independent firing

My component serves as a widget on a dashboard, and I am using *ngFor to render multiple widgets based on the dashboard's data. Each WidgetComponent receives some of its data via @Input() from the parent. parent <app-widget *ngFor="let widget ...

"Endowed with improper dimensions, the BootStrap collapse feature

Yesterday, I posted about an issue with BootStrap and panel collapsables causing graph sizes to become distorted. The post was locked because there was no accompanying code. I have now created a code snippet for you all to see the exact problem I am facing ...

What could be causing me to receive no results?

Currently, I am expanding my knowledge in JavaScript, Ajax, and NodeJs. My current project involves creating a webpage that can display a string retrieved from the server. The server-side code is as follows: var express = require('express'); v ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...

Discover the concealed_elem annotations through the power of JavaScript

As I work on my new website, I am struggling with narrowing down the web code. I came across a solution that seems fitting for what I need, but unfortunately, I can't seem to make it work: I attempted the non-jQuery solution, however, I must be missi ...

Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form? I've tried some solutions like this one, but they didn't work for me. function b64toBlob(b64Data, contentType='', sliceSiz ...

Is it necessary to specify a data type for the response when making an AJAX POST request?

After carefully reviewing my code, I have ensured that all the variables in my JavaScript match and are properly set up. Additionally, I have confirmed that all the variables in my data array for my AJAX request correspond correctly to my $_POST['var& ...

Refreshing content with Ajax when the back button is clicked

Hey everyone, I've been working on an ajax site and I'm having trouble getting the content to reload when the back button is clicked. I'm using Dynamic Drives ajax content script along with a script that changes the URL onclick and a popstat ...

Why is it necessary to decode JSON stringified objects in Vue props?

When passing a stringifyed object via props to a component, it seems like there is an issue with the data transformation. <my-component :filter="stringobject" ></my-component> stringobject = "{"search_text":"(ciCl ...

Start up Angular with a Fire $http.get when the page loads

I am facing an issue where my $http.get() request is firing after the home page has already loaded. How can I ensure that the request fires before the page loads so I can utilize the returned data on the page? Here is a snippet of the routing code: var l ...

Drop Down Automation with Selenium IDE

Currently in the process of automating a User Acceptance Testing (UAT) for a software project at my company. I've completed all the typical tasks like recording actions and clicking on buttons, but ran into an issue with a drop-down menu. The problem ...

A timer created using jQuery and JavaScript

Looking for a way to automatically transition between three div elements with a fade in/out effect every 8 seconds? Check out this simple code snippet I wrote: $(".link1").click(function () { $(".feature1").fadeIn(1000); $(".feature2").fadeOut(1000) ...

The error "500 window is not defined in Nuxt3 when using the composition API"

Is it possible to detect the user's preference for color scheme and set a data-mode attribute on the document root (html)? I've been struggling with this. In my app.vue code, I have the following: <template> <div> <NuxtLayout /> ...

Create a feature that allows users to search as they navigate the map using Leaflet

Exploring the idea of incorporating a dynamic "Search as I move the map" feature similar to Airbnb using Leaflet. Striving to strike a balance between loading data relevant to the displayed portion of the map and minimizing unnecessary API requests trigger ...