Sorting posts by creation date with Contentful

24 views Asked by At

I'm using Contentful to manage blog posts for a site I'm making. I set up the content model and have it displaying well on my page, but if I update an old post it moves it to the top of the page. They're being sorted by recent updates, not by creation dates. Is there a way to change how they're sorted on the site? Or will I have to manage that in my code?

Here is my code to get the posts:

const getPosts = async () => {
    try {
      const response = await client.getEntries({
        content_type: "contentType",
      });
      const posts = response.items.map((content) => {
        const title = content.fields.postTitle;
        const post = content.fields.postContent.content;
        const date = content.fields.date;
        const headerImagesObject = content.fields.photoSlideshow;
        const id = content.sys.id;
        const imageFileArray = [];
        headerImagesObject.forEach(function (image) {
          const file = image.fields.file.url;
          imageFileArray.push(file);
        });
        return { title, date, post, imageFileArray, id };
      });
      setPosts(posts);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

then to put them on the page I have this:

<div>
        {posts.map((content) => {
          const { title, date, post, imageFileArray, id } = content;
          return (
            <article
              key={id}
              className="mb-24 mx-6 xl:mx-64 lg:mx-32 bg-blog-bg px-12 py-12 rounded"
            >
              <div className="xl:flex xl:flex-col xl:items-center">
                <Splide
                  className="slideshow-container"
                  options={{
                    gap: "1rem",
                    type: "loop",
                    width: "50vw",
                    autoplay: true,
                    pagination: false,
                    speed: 3000,
                    interval: 4000,
                    pauseOnHover: true,
                    pauseOnFocus: true,
                  }}
                >
                  {imageFileArray.map((image) => {
                    return (
                      <SplideSlide key={image}>
                        <div>
                          <img src={image} alt="image" />
                        </div>
                      </SplideSlide>
                    );
                  })}
                </Splide>
                <div className="flex justify-between items-center my-6 flex-col">
                  <h3 className="text-4xl font-bold">{title}</h3>
                  <h5>{date}</h5>
                </div>
                <div className="post-container">
                  {post.map((content) => {
                    let nodeType = content.nodeType;
                    if (nodeType == "embedded-asset-block") {
                      let bodyImage = content.data.target.fields.file.url;
                      let imageDesc = content.data.target.fields.title;
                      return (
                        <img
                          src={bodyImage}
                          alt={imageDesc}
                          key={imageDesc}
                          className="h-64 m-4 rounded"
                        />
                      );
                    }
                    if (nodeType == "paragraph") {
                      let pContent = content.content[0].value;
                      if (pContent == "") {
                        return <hr key={pContent} className="opacity-0"></hr>;
                      } else {
                        return <p key={pContent}>{pContent}</p>;
                      }
                    }
                    if (/^heading-[1-8]$/.test(nodeType)) {
                      let nodeTypeArray = Array.from(nodeType);
                      let headerType = nodeTypeArray[nodeTypeArray.length - 1];
                      let headerValue = content.content[0].value;
                      let headerClasses = `text-2xl`;
                      if (headerType === "1") {
                        headerClasses = `text-4xl font-bold my-4`;
                      } else if (headerType === "2") {
                        headerClasses = `text-3xl font-semibold my-4`;
                      } else if (headerType === "3") {
                        headerClasses = `text-2xl font-semibold my-4`;
                      } else if (headerType === "4") {
                        headerClasses = `text-1xl font-semibold my-4`;
                      } else if (headerType === "5") {
                        headerClasses = `text-xl font-semibold my-4`;
                      }
                      return React.createElement(
                        `h${headerType}`,
                        { key: headerValue, className: headerClasses },
                        headerValue
                      );
                    }
                  })}
                </div>
              </div>
            </article>
          );
        })}
      </div>

Not sure if that was helpful. But I don't know how to order them the right way. Why is Contentful sorting by update??

1

There are 1 answers

0
radar On

You can achieve this by adding the order parameter to your client.getEntries function like so:

const getPosts = async () => {
    try {
      const response = await client.getEntries({
        content_type: "contentType",
        order: 'sys.createdAt'
      })
  // rest of your code goes here

}

If you want that in reverse, use:

const getPosts = async () => {
      try {
         const response = await client.getEntries({
           content_type: "contentType",
           order: '-sys.createdAt'
         })
     // rest of your code goes here
    
    }