Getting ReferenceError: fetch is not defined

14,846

Solution 1

react-native has fetch default, but test environment on node.js does not have fetch.

You can import fetch like following at the top of test code.

const fetch = require('node-fetch')

The file react-native-interface.js only declare the type of fetch.

declare var fetch: any;

Solution 2

For some cases, in a universal application for both, client and server the maintainers have to use isomorphic-fetch module to their Node project because of Node does not contain Fetch API yet. For more information read this question and answer

But in this special case, hence, React Native, it is some different, Because, in the mobile device area, there is no V8, SpiderMonkey or Node. There is JavaScriptCore. So, for this new situation should be used react-native-fetch.

It is a little different, install it with below code:

npm install react-native-fetch

And then, use it like a JSX component:

import Fetch from 'react-native-fetch'
...
  <Fetch
      url="https://jsonplaceholder.typicode.com/posts/1"
      retries={3}
      timeout={3000}
      onResponse={async (res) => {
        const json = await res.json()
        console.log(json)
      }}
      onError={console.error}
  />

It's so new, but lovely.

Share:
14,846

Related videos on Youtube

Anto
Author by

Anto

click here to edit

Updated on November 06, 2020

Comments

  • Anto
    Anto over 3 years

    In my Saga test for my react native application (that does work correctly) I have added the following test that calls a function that perform a POST http call (doScan).

    describe('Scan the product and register the scanning action', () => {
      const it = sagaHelper(scanProductSaga(scanProductAction(item)));
    
      it('logscan via ASL', (result) => {
        expect(result).toEqual(cps(ASLogger.logScan, xxx));
        return logScanResult;
      });
    
      it('should register the product', (result) => {
        expect(result).toEqual(call(doScan, logScanResult));
      });
    });
    

    Separate file:

    const doScan = scanObj =>
      toJSON(fetch('https://xxxx.xxxxxx.com/logger/scans', {
        method: 'POST',
        headers: new Headers(CONTENT_TYPE_HEADERS),
        body: JSON.stringify(scanObj),
      }));
    

    Note: the fetch function is from 'react-native-interfaces.js' within the react-native library. The test fails and the error is caused by the following exception :

    ReferenceError: fetch is not defined
          at doScan (/Users/andy/WebstormProjects/ASAP/api/index.js:81:11)....
    

    What can cause such issue? What the solution may be?