Next.js Discord

Discord Forum

Prevent page not found when reload dynamic page

Unanswered
Bonga shad posted this in #help-forum
Open in Discord
Bonga shadOP
Hi, I’m trying to change this project to use SSG or client rendering. But I got a problem when running yarn serve out when reload the page, I got 404. How can I prevent this?

Any help appreciated. Thank you very much!

pages>block>[height_or_hash].tsx

import dynamic from 'next/dynamic';
import React from 'react';

const Block = dynamic(() => import('ui/pages/Block'), { ssr: false });

const Page = () => {
  return (
    <div>
      <Block/>
    </div>
  );
};

export default Page;


other component link to this page like this

<Skeleton isLoaded={ !isLoading } display="inline-block">
    <LinkInternal href={ route({ pathname: '/block/[height_or_hash]', query: { height_or_hash: String(data.height), tab: 'txs' } }) }>
       { data.tx_count }
    </LinkInternal>
</Skeleton>

1 Reply

Bonga shadOP
Here's another way I do, but I got 404 every time I reload the page.

/* eslint-disable @typescript-eslint/no-explicit-any */
import React from 'react';

import type { Block, BlocksResponse } from 'types/api/block';
interface Props {
  data: Block;
}
function Block({ data }: Props) {
  return (
    <div>
      { /* Render data from props */ }
      <h1>{ data.height }</h1>
      <p>{ data.hash }</p>
    </div>
  );
}

export async function getStaticPaths() {
  // Fetch the dynamic paths
  const response = await fetch(`http://localhost:4000/api/v2/blocks`);
  const result = await response.json() as BlocksResponse;
  const items = result.items;

  const paths = items.map((item: { height: { toString: () => any } }) => ({
    params: {
      height_or_hash: item.height.toString(),
    },
  }));

  return {
    paths,
    fallback: 'blocking', // Enable CSR for dynamic paths
  };
}

export async function getStaticProps({ params }: any) {
  // Fetch data for the specific path
  const response = await fetch(`http://localhost:4000/api/v2/blocks/${ params.height_or_hash }`);
  const data = await response.json() as Block;

  // Pass the fetched data as props to the page
  return {
    props: {
      data,
    },
  };
}

export default Block;