Proper way of passing asynchronous data in nextjs to pages

Viewed 520

current directory setup:

- components
    - NavBar
    - Header
    - Layout
- pages
    - pages
        - demo.js
- _app.js
- index.js
// index.js
import React from 'react';
import NewLayout from "../../components/NewLayout/NewLayout.js";
import $nacelle from '../../services/nacelle';

const Index = ({page}) => (
    <>
        <NewLayout header={page} />
        <pre>{JSON.stringify(page.id, null, 2)}</pre>
    </>
);

export async function getStaticProps({ context }) {
    try {
        const page = await $nacelle.data.content({
        handle: 'header_us_retail',
        type: 'header'
      });
    
        return {
          props: { page }
        };
    } catch {
        // do something useful if it doesnt work
        const page = 'failed';
        return {
          props: { page }
        };
    }
}

export default Index;

I am importing Layout into the index.js file, loading asynchronous data and passing it to layout as props that will then be used to render the header and navbar (which are imported by the layout component). This works as expected in the index file, however I want this same functionality to work in the demo.js file and any other file I create in pages or elsewhere. Most likely the issue is how I'm trying to use Nextjs and React (new to both), any help would be greatly appreciated.

1 Answers

Turns out the issue was with how Nacelle was accessing the environment variables, so not a NextJS, or React issue.

According to the devs there are multiple ways to expose the environment variables and the following method solved my particular issue:

// file in root: next.config.js
module.exports = {
  env: {
    NACELLE_SPACE_ID: process.env.NACELLE_SPACE_ID,
    NACELLE_GRAPHQL_TOKEN: process.env.NACELLE_GRAPHQL_TOKEN,
    NACELLE_ENDPOINT: process.env.NACELLE_ENDPOINT,
  },
};
Related