Craig P H
Craig P H

Reputation: 141

next js react app fetch not defined error

I am trying to clone the following next.js react app and run it on localhost:3000

https://github.com/elee-ittdublin/lab6-nextjs

when I open localhost:3000 I get the following error

Unhandled Rejection (ReferenceError): fetch is not defined Function._callee$ ./pages/index.js:22

20 | // see https://nextjs.org/learn/basics/fetching-data-for-pages
>22 | Index.getInitialProps = async function() {
24 |   const url = 'https://api.tvmaze.com/search/shows?q=batman';

I have tried to research what I am doing wrong but I still can not fix my problem. Can anyone see where I am going wrong?

Cheers

Upvotes: 4

Views: 8052

Answers (3)

eneski
eneski

Reputation: 1655

fetch is a predefined method in the browser but your function works in server side, so it does not work.

There is an npm package that basically combines browser's fetch and node-fetch together, it is named isomorphic-unfetch, you can install it via the command npm install isomorphic-unfetch.

After that use unfetch method anywhere u want to use fetch method.

PS: In the newer versions of Next.JS ( 10.0.0 and above ) you should not see this problem.

Upvotes: 1

gdfgdfg
gdfgdfg

Reputation: 3566

If you go to the examples here examples and search for fetch, you will see what they are using. In the examples is node-fetch - node-fetch

Upvotes: 2

Jayanta Baishya
Jayanta Baishya

Reputation: 97

May be the package is not installed. Try installing https://www.npmjs.com/package/isomorphic-unfetch

Upvotes: 0

Related Questions