đŸ‘‹ Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Error with useLoaderData() hook when fetching data for blog posts

16 replies
Last updated: Oct 11, 2022
Not sure what's going on here, because the same code is working on another page but I am currently getting this error:

TypeError: Cannot destructure property 'posts' of '(0 , import_react27.useLoaderData)(...)' as it is undefined.
For this code:


import { useLoaderData } from "@remix-run/react";
import { Link } from "@remix-run/react";
import moment from "moment";
import { getClient } from "~/lib/sanity/getClient";
import { urlFor } from "~/lib/sanity/sanity";

// loader() must be async!
export async function loader() {
  const posts = await getClient().fetch(
    `*[_type == "post"]{ 
      _id, 
      title, 
      slug, 
      author,
      "authorName": author->name,
      "authorImage": author->image,
      mainImage, 
      publishedAt, 
      categories,
      excerpt, 
      myTags, 
      featuredPost,
      "categoryName": *[_type == 'category' && _id in ^.categories[]._ref]{title, slug},
    } | order(publishedAt desc) `
  );

  return { posts };
}

export default function LatestBlogPosts() {
  let { posts } = useLoaderData();

return (
    <section className="">
      <div className="relative pt-16 pb-20 px-4 sm:px-6 lg:pt-24 lg:pb-28 lg:px-8">
        <div className="absolute inset-0">
          <div className="h-1/3 sm:h-2/3" />
        </div>
        <div className="relative mx-auto">
          <div className="text-left">
            <h2 className="text-7xl tracking-tight font-black text-richBlack">
              ALL POSTS
            </h2>
          </div>
          <div className="mt-12 grid gap-5 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 lg:max-w-none">
            {posts?.length > 1
              ? posts.slice(0, 12).map((post: any) => (
Any help?
Oct 11, 2022, 9:34 PM
The strange thing about this is that I'm copying it from another part of the website where it works just fine, only changing a few things here...
Oct 11, 2022, 9:34 PM
This is another error it's showing me regarding the same issue

TypeError: Cannot destructure property 'posts' of '(0 , import_react27.useLoaderData)(...)' as it is undefined.
Oct 11, 2022, 9:40 PM
It looks like everything should work. Do you want to post the code from the other file that’s working?
Oct 11, 2022, 10:01 PM
Sure! Here you go:
import { useLoaderData } from "@remix-run/react";
import { Link } from "@remix-run/react";
import moment from "moment";
import NavbarIndex from "~/components/navigation-index";
import { CgArrowLongLeft, CgArrowLongRight } from "react-icons/cg";

import { getClient } from "~/lib/sanity/getClient";

import { urlFor } from "~/lib/sanity/sanity";
import { ReactChild, ReactFragment, ReactPortal } from "react";

// loader() must be async!
export async function loader() {
  const posts = await getClient().fetch(
    `*[_type == "post"]{ 
      _id, 
      title, 
      slug, 
      author,
      "authorName": author->name,
      "authorImage": author->image,
      mainImage, 
      publishedAt, 
      categories,
      excerpt, 
      myTags, 
      featuredPost,
      "categoryName": *[_type == 'category' && _id in ^.categories[]._ref]{title, slug},
    } | order(publishedAt desc) `
  );

  return { posts };
}

export default function BlogIndex() {
  let { posts } = useLoaderData();
  const dateFormatter = new Intl.DateTimeFormat("en-GB");

  return (
    <main className="">
      <NavbarIndex />
      <div className="relative pt-16 pb-20 px-4 sm:px-6 lg:pt-24 lg:pb-28 lg:px-8">
        <div className="absolute inset-0">
          <div className="h-1/3 sm:h-2/3" />
        </div>
        <div className="relative mx-auto">
          <div className="text-left">
            <h2 className="text-7xl tracking-tight font-black text-richBlack">
              ALL POSTS
            </h2>
          </div>
          <div className="mt-12 grid gap-5 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 lg:max-w-none">
            {posts?.length > 1
              ? posts.slice(0, 12).map((post: any) => (
Oct 11, 2022, 10:04 PM
Could you
console.log(posts)
in your loader function before the return to make sure the fetch is working?
Oct 11, 2022, 10:13 PM
);
 console.log(posts)
  return { posts };
}
here?
Oct 11, 2022, 10:15 PM
Yes. Then when you visit that page, it should log something to your terminal (where you ran
npm run dev
or its equivalent).
Oct 11, 2022, 10:15 PM
Is the working file in
routes
and the other in
components
?
Oct 11, 2022, 10:20 PM
Yes!
Oct 11, 2022, 10:21 PM
Is it fixed once you move it to routes?
Oct 11, 2022, 10:25 PM
No, same error
Oct 11, 2022, 10:27 PM
Should I just start this component over from scratch? I feel like it should absolutely be working
Oct 11, 2022, 10:33 PM
The one that is working is basically the page to show ALL the blog posts, this component is to show only 3 on the index page
Oct 11, 2022, 10:34 PM
Proof that it's returning data on the page that's working:
Oct 11, 2022, 10:42 PM
I had to export the loader on the index route
Oct 11, 2022, 11:35 PM
this works now
Oct 11, 2022, 11:35 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?