Get X number of custom types

Hey there,

I'm trying to create a page that fetches X number of custom types, then there is a "load more" button on the page to fetch x number more until all custom types are loaded.

I think I'm getting close but I've hit a wall as not sure what to be looking for.

This code does work I think but it fetches all custom-type items.

If someone could help point me in the right direction I'd really appreciate it.

Here is my code so far:

import Header from "../components/header";
import Footer from "../components/footer";
import styles from "./news.module.css";
import { useEffect, useState } from "react";
import { createClient } from "../prismicio";
import BlogTile from "../components/blog-tile";


const News = () => {
  const [articles, setArticles] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);

  const loadMoreArticles = async () => {
    console.log('Loading more articles');
    setIsLoading(true);

    try {
      const client = createClient(); // Create the Prismic client
      const response = await client.getAllByType('blog'
    );

      ///console.log(response); // Log the response object

      const newArticles = response.map((result) => ({
        id: result.id,
        // Map additional properties here
        thumbImage: result.data.blogimage.url,
        category: result.data.category,
        readTime: result.data.timetoread,
        articleTitle: result.data.title,
        //authorAvatar: result.data.author.data.avatar.url,
        //authorName: result.data.author.data.authorname,
        releaseDate: result.data.releasedate,
        articleShortDescription: result.data.summary,
        uid: result.data.uid,
      }));

      if (newArticles.length === 0) {
        setHasMore(false);
      } else {
        setArticles((prevArticles) => [...prevArticles, ...newArticles]);
        setPage((prevPage) => prevPage + 1);
      }
    } catch (error) {
      console.error('Error while fetching articles:', error);
    }

    setIsLoading(false);
  };

  // Initial load of articles
  useEffect(() => {
    console.log("*** Initial load of articles ***");
    const fetchArticles = async () => {
      setIsLoading(true);
      try {
        const client = createClient(); // Create the Prismic client
        const response = await client.getAllByType('blog'
      );
  
        ///console.log(response); // Log the response object
  
        const mappedArticles = response.map((result) => ({
          id: result.id,
          // Map additional properties here
          thumbImage: result.data.blogimage.url,
          category: result.data.category,
          readTime: result.data.timetoread,
          articleTitle: result.data.title,
          //authorAvatar: result.data.author.data.avatar.url,
          //authorName: result.data.author.data.authorname,
          releaseDate: result.data.releasedate,
          articleShortDescription: result.data.summary,
          uid: result.data.uid,
        }));

        setArticles(mappedArticles);
        setPage(1);
      } catch (error) {
        console.error('Error while fetching articles:', error);
      }

      setIsLoading(false);
    };

    fetchArticles();
  }, []);

  return (
    <div>
      <Header/>
      <h1>Latest news</h1>
      <div>
        {articles.map((article) => (
          <div key={article.id}>{
            /* Render your article here */
            <BlogTile
              // Pass additional parameters
              thumbImage={article.thumbImage}
              category={article.category}
              readTime={article.readTime}
              articleTitle={article.articleTitle}
              authorAvatar={article.authorAvatar}
              authorName={article.authorName}
              releaseDate={article.releaseDate}
              articleShortDescription={article.articleShortDescription}
              uid={article.uid}
            />
            }
          </div>
        ))}
      </div>
      {isLoading && <p>Loading...</p>}
      {!isLoading && hasMore && (
        //Load more button
        <button className={styles.button} onClick={loadMoreArticles}>
          <b className={styles.button1}>Load more</b>
        </button>
      )}
      {!isLoading && !hasMore && <p>All articles loaded.</p>}
      <Footer/>
    </div>
  );
};

export default News;

:wave:
Hello @willbrettdesign.
I think this should help you:

Thanks so much! Will give this a go tomorrow! :slight_smile:

Hello @willbrettdesign

Have you tried the solution? Do you still need any assistance?

@vagmen27 Thanks for the response.

Thanks,
Priyanka

1 Like