Next.js Discord

Discord Forum

<Suspense> question. How to make a better loading UI?

Unanswered
Pulx/Mars posted this in #help-forum
Open in Discord
Hello! I have a quick question.
So, I make the requests in my main page then pass the data to the components to avoid multiple requests to the database.
Ex:
export default function Home() {
  const [artists, setArtists] = useState<Author[]>([]);
  const [loadingArtists, setLoadingArtists] = useState<boolean>(true);
  useEffect(() => {
    getArtists().then((data: any) => {
      setArtists(data);
      setLoadingArtists(false);
    });
},[])
return(
<main>
<Component data = {artists} structure={1} loadingStatus={loadingArtists}/> //It display a specific component structure like it removes some elements and add others, it's for a slider component and in structure 1 I show the artists and theyr main opera of art and the title of the opera with the age of creation (specific) 
<Component data = {artists} structure={2} loadingStatus={loadingArtists} /> //Only show the artists and a specific bg for the artist like a banner and his name/age of birth/death.
</main>
)
}

So, as you can see, I only make one request instead of 2 or 4 if I put the server action inside the component!
To make a skeleton, I use the "loadingStatus" (boolean) to identify if data was provided.
Here's a quick example:
{loadingState ? showSkeleton : <p> Lorem Impus {data.title}</p>


my question is, can't I make a better loading system? Like using suspense or something like that. I wanna create a great app. I tried suspense, but I don't make any request in the component so it might be useless for me.

What do you think?

4 Replies

Northeast Congo Lion
If done correctly from server component (page) and static you will have no need to use suspense or a loading page to be honest
you could write an async function like async function GetData() {}
and put this logic inside that function:

  setArtists(data);
      setLoadingArtists(false);
    });
then inside Home() function you can do:

const data = await GetData();