Skip to content

Instantly share code, notes, and snippets.

@akellbl4
Created March 7, 2021 10:16
Show Gist options
  • Save akellbl4/80ce515641070307279494562289ed62 to your computer and use it in GitHub Desktop.
Save akellbl4/80ce515641070307279494562289ed62 to your computer and use it in GitHub Desktop.
Code example for the article: "Why I got rid of getInitialProps on my work Next.js project"
async function fetchUser(params) {
const res = await fetch('https://example.com/api/user', params);
const data = await res.json();
return data;
}
async function fetchUserFromServer(ctx) {
const { token } = ctx.req.cookies;
const user = await fetchUser({ headers: { Authorization: `Bearer ${token}` } });
return user;
}
// with server side rendering
export async function getServerSideProps(ctx) {
const user = await fetchUserFromServer(ctx);
return {
props: { user },
};
}
function Profile({ user }) {
return <div>{user.name}</div>;
}
// with static rendering
function Profile() {
const [user, setUser] = useState();
useEffect(() => {
fetchUser().then((u) => setUser(u));
}, []);
if (user === undefined) {
// we may create skeleton with react-content-loader here
return <div>Loading...</div>;
}
return <div>{user.name}</div>;
}
@iiDestiny
Copy link

Thank you for your reply.

I may have to think about it, I haven't found a best practice solution yet. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment