Using Context Providers (in _app.js
) with Dynamic Routes?
#14529
-
Hello all, I am using a Context Provider in my import React from 'react';
import App from 'next/app';
import { AuthProvider } from '../hooks/useAuth';
export default class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<AuthProvider>
<Layout>
<Component {...pageProps} />
</Layout>
</AuthProvider>
);
}
} However, when I attempt to generate dynamic routes (from data in DatoCMS) that require a user to be authorized, the Context is not available. import { useAuth } from '../../hooks/useAuth';
import { getPageBySlug, getAllPagesWithSlug } from '../../lib/api';
function DynamicPage({ page }) {
const { user } = useAuth();
// Stripped out a bunch of components/content here, but this is the general idea
return (
<>
{user ? (
<div>
<h2>{page.title}</h2>
<p>{page.content}</p>
</div>
) : null}
</>
);
}
export async function getStaticProps({ params }) {
const page = (await getPageBySlug(params.slug)) || {};
return {
props: {
page,
},
};
}
export async function getStaticPaths() {
const pages = await getAllPagesWithSlug();
return {
paths: pages?.allPages.map((page) => `/page/${page}`) || [],
};
}
export default DynamicPage; The pages are generated but are no longer rendered properly because they don't have information about the Context Provider. I'd also like to add that this works as expected in local dev. Would creating a HOC help with the issue? Any help here would be appreciated. Cheers! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Could you try move the |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
@laurendorman I have the same problem in multiple pages, have you found a solution for that? |
Beta Was this translation helpful? Give feedback.
getStaticProps
andgetStaticPaths
get executed at build time so there is no way for Next to know about what user will be viewing the page. It worked locally becausegetStaticProps
andgetStaticPaths
are called on every request during local dev.