Created
March 7, 2021 10:16
-
-
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"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for your reply.
I may have to think about it, I haven't found a best practice solution yet. Thank you.