3

I am building an application to showcase the usage of the Suspense in Nextjs 13. But the Suspense fallback is not showing while loading.

Here is the page.js

import React, { Suspense } from "react";
import Loading from "./loading";
const Trending = React.lazy(() => import("./Trending"));

function Page() {
  return (
    <div>
      <Suspense fallback={<Loading />}>
        <Trending />
      </Suspense>
    </div>
  );
}

export default Page;

Here is the Trending

import axios from "axios";

export default async function Trending() {
  const res = await axios.get(
    `https://api.themoviedb.org/3/trending/movie/day?api_key=1428e09fe38be9df57355a8d6198d916`
  );

  const data = res.data;

  // Add a delay to ensure that the Suspense fallback is shown
  await new Promise((resolve) => setTimeout(resolve, 3000));

  return (
    <div>
      <li>{data.results[0].title}</li>
    </div>
  );
}

If you need anything else let me know.

I tried various method such as lazy loading, adding delay and all but still not working. I need to see the fallback component showing while loading the data.

2 Answers2

2

Since you are using NextJS, you should use their own API for lazy loading components. Which you can find in their docs.

With your component it looks like this:

// ..imports..
import dynamic from 'next/dynamic'
const Trending = dynamic(() => import('./Trending'), {
    ssr: false,
})

NextJS renders your component first on server side and then on client, therefore it'd make 2 identical requests.

To avoid this behavior you need to set ssr option, that's why:

ssr: false

And then in your jsx:

 // ..jsx..
 <Suspense fallback={<Loading />}>
    <Trending />
 </Suspense>
 // ..jsx..
Marekus
  • 31
  • 5
0

Maybe you should throw a Promise in order to take effect the suspense. As what Nicholas Tower said on this link. React Suspense is not working as intended

kelsky
  • 83
  • 7