Nextjs is a react-node framework (i.e. it combines reactjs and nodejs so that your project is all in one place).
If you have tried Data fetching with Nextjs, then you will notice that there are recommended methods. These are getInitialProps
, getStaticProps
, getStaticPaths
and getServerSideProps
.
I am coming from a react background and implementing these methods are still giving though time - they are not working. However, using the regular react
fetch method (i.e. componentDidMount()) works for me perfectly.
So I am curious. I want to know if this is okay or must I use the recommended nextjs fetching methods?
Top comments (13)
Nextjs data fetching methods are used for static and server side rendering. It’s ok to fetch data in componentDidMount or useEffect if you don’t really need static/server side rendering.
Thank you Bino. 🤗
Is there a way you can enlighten me on this static/server rendering thing?
Like I want to know why it is a better way of doing things
It you fetch the data in getInitialProps then your html has the data.
Benefits:
Thank you Saurabh. These benefits sounds so awesome 🤗
I will dig more to find out why it’s not working for me 🤦🏻♂️😊
I can't say why it isnt working for you.
But from my debugging experiences in next.js, i will say fetch on server isnt same as fetch on client
Wow... Any suggestions on what I might have to try out?
What are you using for data fetching?
If apollo then see next.js apollo example, apollo needs additional code for SSR
I use node-fetch.
Maybe I should tryout Appolo then
Apollo is only for graphql
Are you getting any error?
No errors. Nothing comes up in my console at all.
That’s more reason why it is frustrating 😆
node-fetch
is specifically a NodeJS library. With Next, if a page is rendered on the server, it will run in a Node environment. If it's rendered by the browser, it will run in the browser.If you try to use
node-fetch
in the browser, it will probably fail. What you can try is to replacenode-fetch
withisomorphic-fetch
, which will give you an equivalentfetch
method you can safely use in both environments.Thank you Louis. I will check that out