20

Is there a way we can have a loading state similar to when fetching data on the client-side?

The reason I would like a loading state is to have something like a loading-skeleton with for instance react-loading-skeleton

On the client-side we could do:

import useSWR from 'swr'

const fetcher = (url) => fetch(url).then((res) => res.json())

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

But for SSR (getServerSideProps) I cannot figure out if that is doable for example could we have a loading state?

function AllPostsPage(props) {
  const router = useRouter();
  const { posts } = props;

  function findPostsHandler(year, month) {
    const fullPath = `/posts/${year}/${month}`;

    router.push(fullPath);
  }

  if (!data) return <div>loading...</div>; // Would not work with SSR

  return (
    <Fragment>
      <PostsSearch onSearch={findPostsHandler} />
      <PosttList items={posts} />
    </Fragment>
  );
}

export async function getServerSideProps() {
  const posts = await getAllPosts();

  return {
    props: {
      posts: posts,
    },
  };
}

export default AllPostsPage;

Recently Next.js has released getServerSideProps should support props value as Promise https://github.com/vercel/next.js/pull/28607 With that we can make a promise but am not sure how to implement that and have a loading state or if that is even achievable. Their example shows:

export async function getServerSideProps() {
  return {
    props: (async function () {
      return {
        text: 'promise value',
      }
    })(),
  }
}

Currently watching Next.conf (25/10/2022) this issue looks promising: https://beta.nextjs.org/docs/data-fetching/streaming-and-suspense

2
  • 1
    Does this answer your question? nextjs getServerSideProps show loading Sep 22, 2021 at 10:32
  • No not really, because that is _app.js based. I want it on a page component level. For now the only/best solution is to do it Client-Side. With getServerSideProps there's to much hassle at the moment to get a loading state.
    – Mark
    Sep 23, 2021 at 0:55

6 Answers 6

9

You can modify the _app.js component to show a Loading component while the getServerSideProps is doing async work like a fetch as shown here https://stackoverflow.com/a/60756105/13824894. This will apply on every page transition within your app.

You can still use your loading logic client-side independently.

8

you can set loading state on _app.js

import Router from "next/router";

export default function App({ Component, pageProps }) {
  const [loading, setLoading] = React.useState(false);
  React.useEffect(() => {
    const start = () => {
      console.log("start");
      setLoading(true);
    };
    const end = () => {
      console.log("findished");
      setLoading(false);
    };
    Router.events.on("routeChangeStart", start);
    Router.events.on("routeChangeComplete", end);
    Router.events.on("routeChangeError", end);
    return () => {
      Router.events.off("routeChangeStart", start);
      Router.events.off("routeChangeComplete", end);
      Router.events.off("routeChangeError", end);
    };
  }, []);
  return (
    <>
      {loading ? (
        <h1>Loading...</h1>
      ) : (
        <Component {...pageProps} />
      )}
    </>
  );
}
0

I have not tried this feature yet but in theory I think it should work. If all you want is to have the client side access to a promise via server props, try as below. Basically your props is a async lambda function so you do any work needed e.g fetching data etc inside it so the client-side should access props as a promise and await for it.

    export async function getServerSideProps() {
  return {
    props: (async function () {
           const posts = await getAllPosts();
      return {
        posts: posts,
      }
    })(),
  }
}

//then on client-side you can do the following or similar to set loading state

function MyComponent(props) {

 const [isLoading, setIsLoading] = useState(false);
 const [posts, setPosts] = useState({});

 useEffect(async () => {
   setIsLoading(true);
   const tempPosts = await props?.posts;
   setPosts(posts);
   setIsLoading(false);
}, [])

return (
 {isLoading && <div>loading...</div>}
);

}

export default MyComponent;

3
  • Yes that makes sense. My question/issue is then how'd I implement a loading state e.g. if (!data) return <div>loading...</div>;
    – Mark
    Sep 21, 2021 at 6:12
  • updated previous answer to include client side Sep 21, 2021 at 20:03
  • 1
    props (from getServerSideProps) must be serializable, therefore this is not a valid solution (functions are not serializable by default)
    – Yhozen
    Jul 14, 2022 at 16:31
0

This works for me using MUI v.5

import Router from "next/router";
import Head from "next/head";
import { useEffect, useState } from "react";
import { CacheProvider } from "@emotion/react";
import {
  ThemeProvider,
  CssBaseline,
  LinearProgress,
  CircularProgress,
  circularProgressClasses,
  Box,
} from "@mui/material";
import { alpha } from "@mui/material/styles";
import createEmotionCache from "/src/createEmotionCache";
import theme from "/src/theme";
import Layout from "/src/components/layout/Layout";

// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();

function Loader(props) {
  return (
    <Box
      sx={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
      }}
    >
      <LinearProgress />
      <Box sx={{ position: "relative", top: 8, left: 8 }}>
        <CircularProgress
          variant="determinate"
          sx={{
            color: alpha(theme.palette.primary.main, 0.25),
          }}
          size={40}
          thickness={4}
          {...props}
          value={100}
        />
        <CircularProgress
          variant="indeterminate"
          disableShrink
          sx={{
            animationDuration: "550ms",
            position: "absolute",
            left: 0,
            [`& .${circularProgressClasses.circle}`]: {
              strokeLinecap: "round",
            },
          }}
          size={40}
          thickness={4}
          {...props}
        />
      </Box>
    </Box>
  );
}

function MyApp({
  Component,
  pageProps,
  emotionCache = clientSideEmotionCache,
}) {
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    Router.events.on("routeChangeStart", () => {
      setIsLoading(true);
    });
    Router.events.on("routeChangeComplete", () => {
      setIsLoading(false);
    });
    Router.events.on("routeChangeError", () => {
      setIsLoading(false);
    });
  }, [Router]);

  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        {isLoading && <Loader />}
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </ThemeProvider>
    </CacheProvider>
  );
}

export default MyApp;

enter image description here

-2

My choice is to use isReady method of useRouter object

import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'

function MyApp({ Component, pageProps }) {
  const [isLoading, setIsLoading] = useState(true)
  const router = useRouter()
  useEffect(() => {
    router.isReady && setIsLoading(false)
  }, []
    
  )
  return <>{isLoading ? <>loading...</> : <Component {...pageProps} />}</>
}

export default MyApp
3
  • Nice solution! P.S. You have to add 'router' to the effects dependency array or else it keeps loading indefinitely.
    – iamfredrik
    May 2 at 5:24
  • this is not even the problem Aug 7 at 13:46
  • useEffect hooks don't work on server side components medium.com/swlh/… Aug 28 at 22:42
-2

I've added Jamal Eddine Naamani's answer into a simple custom hook

use-loading.js

import { useRouter } from "next/router";
import { useState, useEffect } from "react";

function useLoading() {
  const [isLoading, setIsLoading] = useState(true);
  const router = useRouter();

  useEffect(() => {
    router.isReady && setIsLoading(false);
  }, []);

  return isLoading;
}

export default useLoading;

And in the original page


export async function getServerSideProps() {
  const data = await getData();

  return {
    props: {
      data: data,
    },
  };
}

const SomePage = ({ data }) => {
  const isLoading = useLoading();

  return (
    <>      
      {isLoading && <LoadingPage />}
      {!isLoading && <SomeComponent data={ data } />}
    </>
  );
};

export default SomePage;
1
  • There is a problem with this type of solution since it won't render the html on the server-side, in this case, next.js will only send the JSON in the response, and not the actual HTML due to isLoading being set to true
    – Marko
    Jun 7 at 7:44

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.