#404 Page Flashing When Creating SSG Components

33 messages · Page 1 of 1 (latest)

uneven oasisBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

next lynx
#
//server/api/routers/profile.ts
import { Prisma } from "@prisma/client";
import { inferAsyncReturnType } from "@trpc/server";
import { z } from "zod";

import {
  createTRPCContext,
  createTRPCRouter,
  protectedProcedure,
  publicProcedure,
} from "~/server/api/trpc";

export const profileRouter = createTRPCRouter({
  getById: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(async ({ input: { id }, ctx }) => {
      const currentUserId = ctx.session?.user.id;
      const profile = await ctx.prisma.user.findUnique({
        where: { id },
        select: {
          name: true,
          image: true,
          _count: { select: { followers: true, follows: true, tweets: true } },
          followers:
            currentUserId == null
              ? undefined
              : { where: { id: currentUserId } },
        },
      });

      if (profile == null) return;
      return {
        name: profile.name,
        image: profile.image,
        followersCount: profile._count.followers,
        followsCount: profile._count.follows,
        tweetsCount: profile._count.tweets,
        isFollowing: profile.followers.length > 0,
      };
    }),
});

#

pretty simple routing, setting a procedure for getById to return the profile name, image, and associated data

open glen
#

It seems like you're experiencing an issue with a Single Page Application (SPA) or a Static Site Generator (SSG) where the 404 error page is flashing when you create components. This issue could be caused by a few different factors, and troubleshooting it may require examining your specific setup and code. Here are some common steps to help you identify and resolve the issue:

#
  1. Check Routing Configuration:

    • Ensure that your routing configuration is correctly set up in your SSG framework (e.g., Next.js, Gatsby, Nuxt.js). Verify that you have defined routes for all the components/pages you've created.
    • Pay attention to any catch-all routes ([...slug].js in Next.js, pages/**/*.js in Gatsby) as they might affect 404 behavior.
  2. 404 Page Implementation:

    • Double-check how you've implemented your 404 page. Ensure that it's set up correctly as a catch-all or a fallback route.
    • Verify that the 404 page itself doesn't have any issues causing it to reload or flash.
  3. Client-Side Navigation:

    • If you're using client-side navigation (e.g., with frameworks like React Router or Next.js's Link component), make sure you're handling navigation correctly. In some cases, incorrect navigation handling can lead to 404 flashes.
  4. Dynamic Imports:

    • If you're using dynamic imports for your components, ensure that they are correctly loaded and rendered. Sometimes, issues with code splitting can cause unexpected behavior.
  5. Error Handling:

    • Implement error handling for any data fetching or asynchronous operations that might be causing the issue. A failed API request or data fetching can lead to 404 flashes.
  6. Server Configuration:

    • If you're deploying your SSG to a server, check your server configuration. Ensure that it properly handles routing and doesn't interfere with your SSG's routing.
  7. Browser Developer Tools:

    • Use browser developer tools (e.g., Chrome DevTools) to inspect the network requests and console messages. Look for any error messages or unexpected behavior during navigation.
  8. Cache Issues:

    • Sometimes, caching issues in development or production environments can cause unexpected behavior. Try clearing your browser cache or using "hard refresh" (Ctrl + F5) to rule out caching problems.
#
  1. Dependency Updates:

    • Ensure that all your dependencies, including your SSG framework and any related packages, are up-to-date. Sometimes, updating dependencies can resolve unexpected issues.
  2. Community and Documentation:

    • Check if others have experienced a similar issue in the community forums or GitHub repositories of the SSG framework you're using. Review the documentation for your specific framework to see if there are any relevant troubleshooting steps.

By systematically investigating these areas, you should be able to identify the root cause of the 404 page flashing issue in your SSG components and take the necessary steps to resolve it.

blissful rampart
next lynx
#

gotcha

blissful rampart
#

should be something like trpc.something.something.useQuery

#

show that part

open glen
next lynx
#

this is my actual profile page routed via pages/profiles/[id].tsx

import type {
  GetStaticPaths,
  GetStaticPropsContext,
  InferGetStaticPropsType,
  NextPage,
} from "next";
import { ssgHelper } from "~/server/api/ssgHelper";
import { api } from "~/utils/api";
import ErrorPage from "next/error";
import Head from "next/head";

const ProfilePage: NextPage<InferGetStaticPropsType<typeof getStaticProps>> = ({
  id,
}) => {
  //**PRISMA CALL DEFINED IN profile ROUTER**
  const { data: profile } = api.profile.getById.useQuery({ id });

  if (profile == null || profile.name == null) {
    return <ErrorPage statusCode={404} />;
  }

  return (
    <>
      <Head>
        <title>{`Twitter Clone - ${profile.name}`}</title>
      </Head>
      {profile.name}
    </>
  );
};

export const getStaticPaths: GetStaticPaths = () => {
  return {
    paths: [],
    fallback: "blocking",
  };
};

export async function getStaticProps(
  context: GetStaticPropsContext<{ id: string }>,
) {
  const id = context.params?.id;
  if (id == null) {
    return {
      redirect: {
        destination: "/",
      },
    };
  }
  
  const ssg = ssgHelper();
  await ssg.profile.getById.prefetch({ id });

  return {
    props: {
      trpcState: ssg.dehydrate(),
      id,
    },
  };
}

export default ProfilePage;
#

the error page should only be returning if the api.profile.getById procedure is unable to find anything. Not if it is loading the page which is the behavior currently exhibited

blissful rampart
#

hmm

next lynx
#

i'll take a vid of what it looks like, it

blissful rampart
#

try this

-  await ssg.profile.getById.prefetch({ id });
+  const data = await ssg.profile.getById.fetch({ id });
+  console.log(data)

what do you get

next lynx
#

it says "[HMR] connected" which I assume means that it's able to contact the server? I'm pretty new to next so sorry if these questions/answers are really trivial/stupid

#

it does so one time on each load of the page

blissful rampart
#

remember to change prefetch to fetch

#

if you are not sure which log that is, add another console.log before it, like

const data = await ssg.profile.getById.fetch({ id });
console.log("hello");
console.log(data);

then it's the one that follows "hello"

next lynx
#

I did, fetch returns simply "[HMR] connected", prefetch returns 2 queries, >> query #1 {obj} and << query #1 {obj}

blissful rampart
#

what?

#

can you screenshot your code and the terminal now

next lynx
#

Ohhhhh I'm actually so fucking stupid, I was looking in the JS console for the print statement when I should be looking in my npm console, give me a sec
this is what the server returns on loading of the page, with prefetch it flicks to the 404 page then to the profile page correctly, with fetch I'm simply getting this error:

#
TypeError: Cannot read properties of undefined (reading 'length')
    at eval (webpack-internal:///./src/server/api/routers/profile.ts:45:44)
    ... 3 lines matching cause stack trace ...
    at async resolve (file:///C:/Users/Alex/Desktop/Next%20Projects/TwitterClone/node_modules/@trpc/server/dist/index.mjs:486:24) {
  code: 'INTERNAL_SERVER_ERROR',
  name: 'TRPCError',
  [cause]: TypeError: Cannot read properties of undefined (reading 'length')
      at eval (webpack-internal:///./src/server/api/routers/profile.ts:45:44)
      at async resolveMiddleware (file:///C:/Users/Alex/Desktop/Next%20Projects/TwitterClone/node_modules/@trpc/server/dist/index.mjs:420:30)
      at async callRecursive (file:///C:/Users/Alex/Desktop/Next%20Projects/TwitterClone/node_modules/@trpc/server/dist/index.mjs:456:32)
      at async callRecursive (file:///C:/Users/Alex/Desktop/Next%20Projects/TwitterClone/node_modules/@trpc/server/dist/index.mjs:456:32)
      at async resolve (file:///C:/Users/Alex/Desktop/Next%20Projects/TwitterClone/node_modules/@trpc/server/dist/index.mjs:486:24)
}
- error src\server\api\routers\profile.ts (37:39) @ length
- error TypeError: Cannot read properties of undefined (reading 'length')
    at eval (webpack-internal:///./src/server/api/routers/profile.ts:45:44)
    ... (L for the character limit)
  name: 'TRPCError',
  digest: undefined
}
  35 |         followsCount: profile._count.follows,
  36 |         tweetsCount: profile._count.tweets,
> 37 |         isFollowing: profile.followers.length > 0,
     |                                       ^
  38 |       };
  39 |     }),
  40 | });
blissful rampart
open glen
#

The error message you're encountering, "TypeError: Cannot read properties of undefined (reading 'length')," suggests that the profile.followers property is undefined, and you're trying to access its length property. This typically happens when you're working with an object or array that hasn't been properly initialized or loaded.

To resolve this issue, you should perform proper null or undefined checks before accessing properties or elements in your code. Here's how you can do that:

if (profile && profile.followers && profile.followers.length > 0) {
  // Access profile.followers safely
  // Your code here
} else {
  // Handle the case when profile.followers is not defined or empty
  // For example, you 
can set a default value or handle the error
}

This conditional check ensures that you only attempt to access the length property when profile and profile.followers are both defined. If profile or profile.followers is undefined, the code inside the else block or any error handling logic will be executed.

Additionally, it's a good practice to verify the data you're working with to avoid unexpected errors like this. Depending on your application's requirements, you might want to handle cases where profile or its properties are undefined more gracefully.

Keep in mind that the root cause of why profile.followers is undefined might require further investigation in your application's data fetching and handling logic.

#

Please tell me if it resolved your issue

next lynx
#

Yea, some time away from the PC and some slight modifications to the length variable to check if it was null as well as some other small tweaks for null checks and displaying the 404 page got it fixed, I greatly appreciate both of your guy's input, time, and help, thank you

uneven oasisBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1152043518525702204 message)