jameshwart lopez
jameshwart lopez

Reputation: 3131

Next.js change url without building the page using ISR

I am using ISR to build static product pages using next.js. Since there are a lot of product page to generate I only generated a few pages for it. The problem that I am trying to solve is the delay in transferring the view to the product page.

So I have a category page and within it have a list of products. On each product card item, I use next.js link so that the user can go to the product page.

The problem here is the delay going to the product page when the page is not yet generated. Going to the product page is slow because next.js is building the page. I want to transfer the user to the product page immediately while showing the loading state of the page via the router.isFallback condition.

What I'm trying to achieve is the same as what a normal link would do because it shows the loading state of the page but I don't want to reload the page.

Upvotes: 0

Views: 971

Answers (2)

KALrious
KALrious

Reputation: 67

What you could do is to make the props not required,

The thing that must take time during the loading of you're ISG page of nextJs is the call api in GetStaticProps, Something like that:

export async function getStaticProps({ params }) {
  const { status, data } = await axios.get<Data>(
    `${server}/data`
  );

  if (status === 404) {
    return { notFound: true };
  }

  return {
    props: {
      ...data
    },
    revalidate: 60,
  };
}

But you could also decide that you will fetch the data during the loading of the state with a fall-back blocking:

const MyPage = (props) => {
 const [data,setData] = useState<Data>(null);
 
 useEffect(() => {
  (function()
   const {data} = axios.get(`${server}/data`);
   setData(data);
  )()
 },[])
 
 return(
 <div>
  !data ? <div>loading ... </div> : <div>Product: {data}</div>
 </div>
 )
}

export async function getStaticProps({ params }){
      return {
        props: {
         isloading: true
        },
        revalidate: 60,
      };
}

Upvotes: 0

Stephen Gbolagade
Stephen Gbolagade

Reputation: 21

Instead of using next/link or router.push, use router.replace

   router.replace(`/product/${id"}`)

Let me know if this work.

Upvotes: 0

Related Questions