404 Page Flashing When Creating SSG Components
Answered
Eurasian Collared-Dove posted this in #help-forum
Original message was deleted.
Answered by Bashamega
The error message you're encountering, "TypeError: Cannot read properties of undefined (reading 'length')," suggests that the
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:
This conditional check ensures that you only attempt to access the
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
Keep in mind that the root cause of why
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.31 Replies
Eurasian Collared-Dove
//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
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 (
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
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.
- 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.
9. 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.
10. 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.
- Ensure that all your dependencies, including your SSG framework and any related packages, are up-to-date. Sometimes, updating dependencies can resolve unexpected issues.
10. 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.
Eurasian Collared-Dove
gotcha
should be something like trpc.something.something.useQuery
show that part
Also if it is not working try reading this
https://stackoverflow.com/questions/67315057/next-js-is-not-building-page-as-ssg-when-it-should
https://stackoverflow.com/questions/67315057/next-js-is-not-building-page-as-ssg-when-it-should
Eurasian Collared-Dove
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
Eurasian Collared-Dove
i'll take a vid of what it looks like, it
try this
what do you get
- await ssg.profile.getById.prefetch({ id });
+ const data = await ssg.profile.getById.fetch({ id });
+ console.log(data)
what do you get
Eurasian Collared-Dove
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
@Eurasian Collared-Dove 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
no not the HMR connected... the
data
should be that profile
in the client side that has been prefetched in the serverremember to change prefetch to fetch
if you are not sure which log that is, add another console.log before it, like
then it's the one that follows "hello"
const data = await ssg.profile.getById.fetch({ id });
console.log("hello");
console.log(data);
then it's the one that follows "hello"
Eurasian Collared-Dove
I did, fetch returns simply "[HMR] connected", prefetch returns 2 queries, >> query #1 {obj} and << query #1 {obj}
what?
can you screenshot your code and the terminal now
Eurasian Collared-Dove
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:
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 | });
@Eurasian Collared-Dove js
//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,
};
}),
});
so what happens here is the
profile.followers
near the end here is undefined
. before returning, console.log(profile)
and see what it looks likeThe error message you're encountering, "TypeError: Cannot read properties of undefined (reading 'length')," suggests that the
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:
This conditional check ensures that you only attempt to access the
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
Keep in mind that the root cause of why
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.Answer
Please tell me if it resolved your issue
Eurasian Collared-Dove
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