TypeError: fields.map is not a function when doing next dynamic sitemap with next-sitemap

223 Views Asked by At

I am trying to do dynamic sitemap for my site and here is my code:

import { GetServerSideProps } from 'next';
import { getServerSideSitemap, ISitemapField } from 'next-sitemap';
import { makeSlugFromString } from '../../lib/helpers';
import { BaseNCategories } from '../../lib/generalConstants';

export const getServerSideProps = async (ctx: any) => {
  const response = await fetch('http://baseapi/v3/category-list');
  const categoriesData = await response.json();
  const categories: any[] = categoriesData.cat;
  const categoryBn = BaseNCategories.filter((baseCategory) => {
    return categories.some((category) => category.CategoryID === baseCategory.CategoryID);
  });
  const fields: ISitemapField[] = categoryBn.map((category) => ({
    loc: `baseApi/${makeSlugFromString(category.Slag)}`,
    lastmod: new Date().toISOString(),
    // priority: 0.7,
    // changefreq: 'daily',
  }));
  console.log({ fields });
  return getServerSideSitemap(ctx, fields);
};

export default function Site() {}

The error I'm getting is "field.map is not a function". I don't know why this is happening. Can anyone help me fix this?

1

There are 1 best solutions below

4
Zaniar Manochehri On

categoryBn is not an array Since categoryBn is derived from BaseNCategories using the filter function, it should always be an array. However, to be certain, you can add a check before creating the fields array to ensure categoryBn is indeed an array.

Replace this:

    const fields: ISitemapField[] = categoryBn.map((category) => ({
  loc: `baseApi/${makeSlugFromString(category.Slag)}`,
  lastmod: new Date().toISOString(),
}));

With this:

    if (!Array.isArray(categoryBn)) {
  console.error('categoryBn is not an array:', categoryBn);
  return { notFound: true }; // Return a 404 page or an error page as needed.
}

const fields: ISitemapField[] = categoryBn.map((category) => ({
  loc: `baseApi/${makeSlugFromString(category.Slag)}`,
  lastmod: new Date().toISOString(),
}));