Ad

Next.js - No Data In Component When Navigating From Other Route

- 1 answer

I'm new to next.js. I'm rendering my page view on the backend side:

module.exports = (server, app) => {
  server.get('/setup', (req, res) => {
    const testData = {
      name: "Test",
      testProp: "testVal",
    };

    return app.render(req, res, '/setup', testData);
  });
};

When I'm refreshing the page on my /setup route in the browser I can see the data inside getInitialProps, this is fine. But when I'm navigating from the other route to /setup route I can't see the data. Why this is happening and how can I change it in order to see the data? Here's my page code:

import { withAuth } from '../utils/withAuth';

const Setup = props => {
  console.log(props); // when linking there is no expected data here
  return(
    <div>Setup here</div>
  )
};

Setup.getInitialProps = async ctx => {
  return { ...ctx.query };
};

export default withAuth(Setup);
Ad

Answer

When navigating from other routes, you are not rendering server-side, so you have to fetch the data from the server in getInitialProps.

import fetch from 'isomorphic-unfetch'

const Setup = (props) => {
  console.log(props);
  return(
     <div>Setup here</div>
  )
}

Setup.getInitialProps = async (ctx) => {
  if (ctx.req) {
   // server-side
   return { ...ctx.query }
  } else {
   // client-side
   const res = await fetch('API/setup')
   const json = await res.json()
   return { ...json }
  } 
}
Ad
source: stackoverflow.com
Ad