0

I've got some data that multiple pages within my app use. Since the fetch time is atrocious, I'd like to fetch that data when someone loads the site, and then pass that data off to multiple different pages to render in different ways.

My understanding from this question is that you aren't able to use getServerSideProps within the _app.tsx. What is the standard for propagating props across your app for NextJS? My guess was to useEffect in the _app.tsx, but that has led to many issues where the data isn't initialized and never updates.

some napkin-code for context

// _app.tsx
function CustomApp({ Component, pageProps }: AppProps) {
  const [data, setData] = useState<DataPoint[]>([])

  useEffect(() => {
    getMyData.then(data => setData(data))
  }, [])

  return (
    <Component {...pageProps} initialData={data}/>
  )
}


// index.tsx
export function Index({initialData}) {
  const [data, setData] = useState(initialData)

  return (
    <Graph {...data} />
  )
}

// anotherPage/index.tsx
export function AnotherPage({initialData}) {
  const [data, setData] = useState(initialData)

  return (
    <Table {...data}>
  )
}
reeslabree
  • 127
  • 13
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage // also you can use the useState hook https://nextjs.org/learn/foundations/from-javascript-to-react/adding-interactivity-with-state – OMi Shah Aug 22 '22 at 17:48
  • You've got 2 options if you want to fetch the data using SSR: 1) Use [`getInitialProps`](https://nextjs.org/docs/advanced-features/custom-app) in `_app`, the data you pass in the props will be available to all pages; 2) Use a re-usable function (or higher-order function) to fetch the data and use it in each page's `getServerSideProps`. – juliomalves Aug 23 '22 at 17:08
  • _"fetch time is atrocious"_ - Note that moving the request to the server inside `getServerSideProps` will most likely still be affected by the long fetch times, and potentially affect your app's TTFB. – juliomalves Aug 23 '22 at 17:12

0 Answers0