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

Mark
  • 731
  • 2
  • 10
  • 29
  • 1
    Does this answer your question? [nextjs getServerSideProps show loading](https://stackoverflow.com/questions/60755316/nextjs-getserversideprops-show-loading) – juliomalves Sep 22 '21 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 '21 at 00:55

6 Answers6

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.

RobLjm
  • 399
  • 2
  • 11
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} />
      )}
    </>
  );
}
Nedim AKAR
  • 123
  • 8
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;

brianangulo
  • 196
  • 1
  • 11
  • Yes that makes sense. My question/issue is then how'd I implement a loading state e.g. `if (!data) return
    loading...
    ;`
    – Mark Sep 21 '21 at 06:12
  • updated previous answer to include client side – brianangulo Sep 21 '21 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 '22 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

atazmin
  • 4,757
  • 1
  • 32
  • 23
-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
-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;
Guy Levin
  • 1,230
  • 1
  • 10
  • 22
  • 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 07 '23 at 07:44