1.0.18 • Published 11 months ago

@react-libraries/use-ssr v1.0.18

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

@react-libraries/use-ssr

overview

Next.js hook for using external data with SSR The difference with 'getStaticProps' is that the same code can be used for both the server and the client when receiving external data.

usage

  • Use App.getInitialProps to receive the fetch data generated by the component

_app.tsx

import { CachesType, createCache, getDataFromTree } from '@react-libraries/use-ssr'
import { AppContext, AppProps } from 'next/app'

const App = (props: AppProps & { cache: CachesType }) => {
  const { Component, cache } = props
  createCache(cache)
  return <Component />
}
App.getInitialProps = async ({ Component, router, AppTree }: AppContext) => {
  const cache = await getDataFromTree(
    <AppTree Component={Component} pageProps={{}} router={router} />
  )
  return { cache }
}
export default App
  • pages/index.tsx
import React from 'react'
import { useSSR } from '@react-libraries/use-ssr'

const Page = () => {
  const [state, setState] = useSSR(
    ['weather', '130000'] /*CacheKeyName*/,
    async (state, setState) => {
      // When this function finishes, the server side will finish processing and SSR will be performed.
      if (state !== undefined) return
      setState(null)
      const result = await fetch(
        'https://www.jma.go.jp/bosai/forecast/data/overview_forecast/130000.json'
      )
      setState(result.json())
    }
  )
  return (
    <div>
      <button onClick={() => setState(undefined)}>Reload</button>
      <pre>{JSON.stringify(state, undefined, '  ')}</pre>
    </div>
  )
}

export default Page
1.0.19

11 months ago

1.0.18

11 months ago

1.0.17

2 years ago

1.0.16

2 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.11

3 years ago

1.0.10

3 years ago

1.0.15

2 years ago

1.0.14

2 years ago

1.0.13

2 years ago

1.0.12

2 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago