Skip to content

Commit

Permalink
Prefetch page data and Djedi nodes in parallel in the example app
Browse files Browse the repository at this point in the history
  • Loading branch information
lydell committed Mar 5, 2019
1 parent 79d35a7 commit 2280eae
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
24 changes: 10 additions & 14 deletions djedi-react/pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,30 +35,26 @@ djedi.options.fetch = unfetch;
// Inject the admin sidebar, if the user has permission.
djedi.injectAdmin();

// This is 99% the standard Next.js boilerplate for _app.js.
export default class MyApp extends App {
static async getInitialProps({ Component, ctx, ctx: { query } }) {
let pageProps = {};

// This demo uses a query parameter for the language to keep the demo small.
// Ugly, but it works.
const language = {}.hasOwnProperty.call(LANGUAGES, query.language)
? query.language
: DEFAULT_LANGUAGE;

if (Component.getInitialProps) {
// Load page data and Djedi nodes in parallel.
const [pageProps] = await Promise.all([
// Pass the language to the child `getInitialProps`, in case it needs to
// call `djedi.prefetch`.
pageProps = await Component.getInitialProps({ ...ctx, language });
}

// Prefetch on all pages. If the page itself has already prefetched (like
// index.js does) this is basically a no-op. If a page absolutely must not
// make network requests, set `.skipDjediPrefetch = true` on it.
if (!Component.skipDjediPrefetch) {
// Make sure to pass the language.
await djedi.prefetch({ language });
}
Component.getInitialProps
? Component.getInitialProps({ ...ctx, language })
: {},
// Prefetch on all pages. If the page takes care of prefetching itself (like
// index.js does), the page should set `.skipDjediPrefetch = true` on
// itself to avoid double network requests.
Component.skipDjediPrefetch ? undefined : djedi.prefetch({ language }),
]);

// Track which nodes are actually rendered.
const nodes = djedi.track();
Expand Down
2 changes: 2 additions & 0 deletions djedi-react/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export default class Home extends React.Component {
storeSlug: PropTypes.string.isRequired,
};

static skipDjediPrefetch = true;

static async getInitialProps({ language }) {
// Imagine this coming from the URL or something.
const storeSlug = "andys-tools";
Expand Down

0 comments on commit 2280eae

Please sign in to comment.