Reputation: 265
I'm trying to import the getServerSideProps method from this page to another and use it throughout multiple pages. How can I do that?
Heres my code:
import DashboardLayout from "@app/layout/DashboardLayout";
import Overview from "@containers/dashboard/Overview";
import { parsedCookie } from "@infrastructure/utils/functions";
const OverviewPage = () => {
return (
<DashboardLayout>
<Overview />
</DashboardLayout>
);
};
export default OverviewPage;
export const getServerSideProps = async (context) => {
const token = parsedCookie(context.req);
const { accessToken, refreshToken } = token;
if (!accessToken || !refreshToken) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
return {
props: {},
};
};
Upvotes: 3
Views: 6838
Reputation: 1
You can create a generic function where you can pass the page which you want to used and fetch data according that prop. i.e
In the NextJs page you can use like this
export const getStaticProps = createGetStaticProps("home")
and the method can be created like this
export function createGetStaticProps(
page: PageType,
): GetStaticProps<any> {
const getStaticProps: GetStaticProps<any> = async (context) => {
// Load any data related to page
const data = await loadData(page, context.params)
return {
props: serializeStaticProps(data),
revalidate: 5000,
}
}
return getStaticProps
}
Upvotes: 0
Reputation: 1214
You can not import getServerSideProps
they are unique for each page but if all pages in first load should get same data you can add getIntialProps
in your _app.js
file.
for more info you can read
customizing _app.js files
Upvotes: 0
Reputation: 265
I found the answer . heres how you can use a pages datafetching method on a another page
import DashboardLayout from "@app/layout/DashboardLayout";
import MyCourses from "@containers/dashboard/MyCourses";
import { getServerSideProps } from "../index";
const MyCoursesPage = () => {
return (
<DashboardLayout>
<MyCourses />
</DashboardLayout>
);
};
export default MyCoursesPage;
export { getServerSideProps };
Upvotes: 12