Skip to content

Instantly share code, notes, and snippets.

@t3dotgg
Created July 12, 2021 00:25
Show Gist options
  • Save t3dotgg/159bf7e57ecd7ff19ce04543eebfdb57 to your computer and use it in GitHub Desktop.
Save t3dotgg/159bf7e57ecd7ff19ce04543eebfdb57 to your computer and use it in GitHub Desktop.
A proposal for a `useBackend` React hook that is compiled out into an API route. Inspired by Vercel and Next.js
// /pages/index.tsx
function ExamplePage() {
const { data } = useBackend(
"get-user-info",
async () => {
const data = await getProfileFromDB();
return data; // {name: string}
},
{ prefetch: true }
);
return <div>{data.name}</div>;
}
// Compiles into 2 files:
// /pages/index.js
function ExamplePage(props) {
const { data } = useQuery(
"get-user-info",
async () => {
const res = await fetch("/api/generated/get-user-info");
const data = await res.json();
return data; // {name: string}
},
{ initialData: props.generated["get-user-info"].initialData }
);
return <div>{data.name}</div>;
}
export default async function getServerSideProps() {
const res = await fetch("/api/generated/get-user-info");
const data = await res.json();
return {
props: {
generated: {
"get-user-info": data,
},
},
};
}
// /pages/api/generated/get-user-info
export default async function (req, res) {
const data = await getProfileFromDB();
res.status(200).json(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment