0

Can't seem to get fetch() working in my React Native app (should work out of the box). Using the new architecture with RN 0.70.4, TypeScript, and a setup to import ES modules.

Every time fetch() is called, this error is printed in the console:

'Tried to call timer with ID %s but no such timer exists.', 6

Using this test button:

      <Button
        title="Test"
        onPress={async () => {
          console.log('PRESSED');

          const promise = fetch('https://www.google.com');
          console.log('promise:', promise);

          try {
            const res = await promise;
            console.log('res:', res);
          } catch (err: unknown) {
            console.log('err:', err);
          }
        }}
      />

When pressed, only PRESSED appears in the console, with no other log messages. In the Flipper network panel, it looks like there is no network call made.

When I add import fetch from 'cross-fetch';, I get 2 lines of console output:

18:17:27.196  32561  appname  PRESSED
18:17:27.210  32561  appname  'promise:', { _h: 0, _i: 0, _j: null, _k: null }

but nothing after that; weirdly, though, the successful network call appears in the flipper network logs.

Any idea what's going on here?!

nerdlinger
  • 1,610
  • 2
  • 17
  • 24
  • i'm using react native's `fetch`, it run normally with your test. I use `"react": "18.1.0", "react-native": "0.70.4"` – Zuet Nov 07 '22 at 04:03

1 Answers1

0

You should use async/await with fetch. You are seeing { _h: 0, _i: 0, _j: null, _k: null } because network call takes some time to execute and you are not using async/await so the response is an unresolved promise. You can also use .then and .catch

  • There is an `await` statement below...why does the promise not resolve or reject when it is awaited there? – nerdlinger Nov 08 '22 at 10:38
  • Why are you fetching google.com? I don't think it will return anything. – Sadia Chaudhary Nov 08 '22 at 11:00
  • It's just for an example to demonstrate why the fetch is not working! Try fetching it; you get an HTML document back typically. – nerdlinger Nov 11 '22 at 19:40
  • I added await before fetch keyword. It did return response but not HTML doc. If it's not working you can use apisause or axios. Both are great. I am suspecting the issue is related with fetch. You can try this example on official doc. https://reactnative.dev/docs/network – Sadia Chaudhary Nov 14 '22 at 05:34