'Fetching API for Articles with NextJS and Strapi

I would like some help on an API issue.

I have been trying to link each Article page based on the content I have created in Strapi CMS on my local server.

The API endpoint that I manage to gather data is from 'http://localhost:1337/api/articles?populate=*'.

Here is my code:

// lib/api.js

export class ApiError extends Error {
  constructor(url, status) {
      super(`'${url}' returned ${status}`);
      if(Error.captureStackTrace) {
          Error.captureStackTrace(this, ApiError);
      }
      this.name = 'ApiError';
      this.status = status;
  }
}

export async function fetchJson(url, options) {
  const response = await fetch(url, options);
  if(!response.ok) {
      throw new ApiError(url, response.status);
  }
  return await response.json();
}


// lib/articles.js
    
import { fetchJson } from "./api";
    
    const API_URL = process.env.API_URL;
    
    // Gets a single article
    export async function getArticle(id) {
        const article = await fetchJson(`${API_URL}/api/article/${id}`);
        return stripArticle(article);
    }
    
    // Gets all articles
    export async function getArticles() {
        const articles = await fetchJson(`${API_URL}/api/articles`);
        return articles.map(stripArticle);
    }
    
    function stripArticle(article) {
        return {
            id: article.id,
            title: article.attributes.Title,
            content: article.attributes.Content,
            pictureUrl: API_URL + article.attributes.Photo.formats.thumbnail.url,
        }
    }

Article Page:

//article/[id].js
import Page from "../../components/Page";
import { getArticle, getArticles } from "../../lib/articles";
import ReactMarkdown from 'react-markdown';
import Moment from 'react-moment';

export async function getStaticProps({ params }) {
    const article = await getArticle(params.id)
    return {
      props: { article },
      unstable_revalidate: 1,
    }
  }

export default function Article({ article }) {
    return (
        <Page title={article.Title}>
            <ReactMarkdown source={article.Content} />
            <p>
              <Moment from="MM Do YYYY">{article.CreatedAt}</Moment>
            </p>
        </Page>
    )
}

export async function getStaticPaths() {
    const articles = await getArticles()
    return {
      paths: articles.map((article) => ({
          params: { id: article.id.toString() }, // Number convert to string
      })),
      fallback: 'blocking', // What if error. Client is blocked, until new page is ready.
  };
 }

I would get an error: TypeError: articles.map is not a function.

If there is a better way to format and write the code, do let me know as I have been trying to find which is best.

Thanks for the help in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source