next-props-composer
v0.1.1
Published
Next.js pageProps composer
Downloads
7
Readme
next-props-composer
Compose multiple Next.js getStaticProps
or getServerSideProps
functions.
Install
npm install next-props-composer
next-props-composer
has a peer dependency of next@^10.0.0
.
Usage
next-props-composer
allows you to compose multiple data-fetching methods for pre-rendering pages.
Export a getStaticProps
or getServerSideProps
function from your page that is mapped to composeProps
.
import { composeProps } from "next-props-composer";
export const getStaticProps = composeProps(foo, bar, baz);
You supply any number of async functions that return props. These are the same function that you would normally return, and the page context is passed to each one.
// lib/api
export const getFoo: GetStaticProps = async ({ params }) => {
const res = await fetch(`/api/foo/${params.id}`);
const foo = await res.json();
return {
props: {
foo,
},
};
};
export const getBar: GetStaticProps = async () => {
const res = await fetch("/api/bar");
const bar = await res.json();
return {
props: {
bar,
},
};
};
And export an async getStaticProps
or getServerSideProps
function on your pages like you usually would. Each props object is merged into one (your props won't be transferable from one function to another. it works async and independently).
// pages/foo/[id].js
import { composeProps } from "next-props-composer";
import { getFoo, getBar } from "lib/api";
function Page({ foo, bar }) {
return <main>{/* Use props like usual */}</main>;
}
export const getStaticProps = composeProps(getFoo, getBar);
export default Page;
While these examples show getStaticProps
, the process is exactly the same for getServerSideProps
.
redirect
and notFound
If one of your composed functions returns a redirect
or notFound
, it will take precedence and immediately return.
export const getFoo: GetStaticProps = async ({ params }) => {
const res = await fetch(`/api/foo/${params.id}`);
const foo = await res.json();
if (!foo) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
return {
props: {
foo,
},
};
};
revalidate
If one or more of your functions returns a revalidate
property to opt into Incremental Static Regeneration, the last resolved value will be passed. This only applies to getStaticProps
.