.map not a function error in getStaticPaths with dynamic routes

6 replies
Last updated: Jul 5, 2022
is it possible to use
.map
in a dynamic page handeling like

[id].js
that contains

getStaticPaths
because when I try that it gives me that the xxx.map is not a function
AI Update

This is a common JavaScript error that happens when you're trying to call .map() on something that isn't an array. In the context of getStaticPaths, this usually means your Sanity query is returning data in an unexpected format.

The Problem

When you fetch data from Sanity for getStaticPaths, you need to ensure your query returns an array. The error "xxx.map is not a function" means the data you're trying to map over is either:

  • undefined
  • null
  • An object instead of an array
  • Not yet loaded

The Solution

Here's the correct pattern for using .map() in getStaticPaths with Sanity queries:

export async function getStaticPaths() {
  // Make sure your query returns an array of slug values
  const paths = await client.fetch(
    `*[_type == "post" && defined(slug.current)][].slug.current`
  );

  return {
    paths: paths.map((slug) => ({ params: { slug } })),
    fallback: true,
  };
}

Common Fixes

1. Check your query syntax

Make sure you're using the [] projection at the end to return an array:

// Good - returns an array of slugs
`*[_type == "post"][].slug.current`

// Bad - might return objects or undefined
`*[_type == "post"].slug.current`

2. Add defensive coding

Always add a fallback in case the query returns nothing:

export async function getStaticPaths() {
  const paths = await client.fetch(
    `*[_type == "post" && defined(slug.current)][].slug.current`
  );

  // Ensure paths is an array before mapping
  const safePaths = (paths || []).map((slug) => ({ params: { slug } }));

  return {
    paths: safePaths,
    fallback: true,
  };
}

3. Debug what you're getting

Add a console.log to see what your query actually returns:

const paths = await client.fetch(`*[_type == "post"][].slug.current`);
console.log('Fetched paths:', paths, 'Type:', typeof paths);

4. Handle multiple content types

If you're querying multiple types, make sure your query still returns an array:

const paths = await client.fetch(
  `*[_type in ["post", "page"] && defined(slug.current)][].slug.current`
);

The key is ensuring that whatever you're calling .map() on is actually an array. The defensive coding approach with (paths || []) is a good safety net that prevents the error even if your query returns unexpected data.

Show original thread
6 replies
Maybe make sure that the data you are trying to map over is available? You can add a ternary ‘?’ to check if its is eg; {categories.map((category) => ( <li key={category}>{category}</li>
))}
Maybe make sure that the data you are trying to map over is available? You can add a ternary ‘?’ to check if its is. I’ve run into this issue quite a bit when trying to map data passed down as a prop, forgetting that props wrap your data in an object.
Yes, you usually map over slugs to generate pages. Here is an example (using TS):
export const getStaticPaths: GetStaticPaths = async () => {
  const data = await sanityClient.fetch(query.documentSlugs, { doc: 'category' })
  const paths = data.map((slug: string) => ({ params: { slug } }))

  return {
    paths,
    fallback: false
  }
}
your query would look something like this:
export const query = `
  *[_type == 'your_document' && defined(slug.current)].slug.current
`
well I have something like this
const CollectionProducts = ({ coldata }) => {
  return (
    <div>
{coldata.map((test) => (
        <div>

        </div>
      ))}
);
};
export const getStaticPaths = async () => {
  // Fetch all the product
  const coldata = await shopifyClient.collection.fetchAllWithProducts();
  const paths = coldata.map((coldata) => ({
    params: {
      title: coldata.title,
    },
  }));

  return {
    paths,
    fallback: "blocking",
  };
};

export const getStaticProps = async ({ params: { title } }) => {
  // Fetch all the product
  const coldata = await shopifyClient.collection.fetchByHandle(title);
  console.log(coldata);

  return {
    props: {
      coldata: parseShopifyResponse(coldata),
    },
  };
};

export default CollectionProducts;
I want to use a map to grab products from my collection but right now it returns

Unhandled Runtime Error
TypeError: coldata.map is not a function

Figured out what the problem was. I needed to target coldata.products.map because I was already in the collection of this fetch

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?