https://github.com/innei/next-suspense
A suspense wrapper for NextJS when change router and fetching data in CSR.
https://github.com/innei/next-suspense
Last synced: about 1 year ago
JSON representation
A suspense wrapper for NextJS when change router and fetching data in CSR.
- Host: GitHub
- URL: https://github.com/innei/next-suspense
- Owner: Innei
- License: mit
- Created: 2022-07-12T08:41:38.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2023-10-25T00:52:27.000Z (over 2 years ago)
- Last Synced: 2025-04-24T04:45:34.884Z (about 1 year ago)
- Language: TypeScript
- Homepage: next-suspense-navy.vercel.app
- Size: 238 KB
- Stars: 6
- Watchers: 3
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: readme.md
- License: LICENSE
Awesome Lists containing this project
README
# Next Suspense
A suspense wrapper for NextJS when change router and fetching data in CSR.
## Motivation
As we know, Next will fetching data in router change, and waiting for request finished then render the next page.
We hope only use blocked fetch data (aka. `getInitialProps`) for first screen of my app because of SSR. And when changing pages (in CSR), it can work as a SPA that will responsive user interactive immediately.

When the Next Router change, and next page has `getInitialProps` method that needed to called. We suspenses it, and render Loading Component immediately and fetching data at the same time. After fetching data successfully, then render Page B.
## Requirement
- NextJS 12 (or 13 disabled app dir)
## Install
```
npm i next-suspense
```
## Usage
```tsx
// utils/wrapper.tsx
import { wrapperNextPage } from 'next-suspense/esm'
export const wrapper: typeof wrapperNextPage = (NextPage, options) =>
wrapperNextPage(NextPage, {
ErrorComponent: (props) =>
Error: {JSON.stringify(props.error)},
LoadingComponent: () => Loading...,
...options,
})
// pages/home.tsx
import type { NextPage } from 'next'
import Link from 'next/link'
import React from 'react'
import { sleep } from 'utils'
import { wrapper } from 'utils/wrapper'
const IndexPage: NextPage<{
bio: string
}> = (props) => {
return (
With Fetching data
Fetched Data:
{JSON.stringify(props.bio, null, 2)}
)
}
IndexPage.getInitialProps = async () => {
await sleep(1000)
return {
bio: 'bio from fetched request',
}
}
export default wrapper(IndexPage)
```
## License
2022 © Innei, Released under the MIT License.
> [Personal Website](https://innei.ren/) · GitHub [@Innei](https://github.com/innei/)