0

I'm trying to use React Native to post an image to a remote API. In order to use fetch(...), I need to turn a public URL into a file object. I use the following code.

const getFile = async (url: string, fileName: string) => {
  const response = await fetch(url, { method: "GET" });
  const data = await response.blob();
  const metadata = {
    type: "image/jpeg",
  };
  const file = new File([data], fileName, metadata);
  return file;
};
const myFile = await getFile("...IMG_URL...", "pic.jpg");

The above code works perfectly well in a browser console. But when I run it using React Native, I get a slightly different behavior. For instance, I can use console.log(myFile) in browser, it prints the file. But, if I run console.log(myFile) in React Native, it does not.

I need the picture to be in a file object because I need to use it in a subsequent fetch(...) call:

const bodyData = new FormData();
bodyData.append("userId", "1");
bodyData.append("logId", "1");
bodyData.append("file", myFile);
const response = await fetch(
  "...API_URL...",
  {
    method: "POST",
    body: bodyData,
  }
);

However, running this causes the following error, which I am unable to interpret:

Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue

I know that this is not a problem with connecting to the server because if I run the same code without the "file" header, it successfully connects to the API server.

It has been recommended that I use rn-fetch-blob, but I can not do this because rn-fetch-blob is not compatible with Expo.

Theone
  • 111
  • 4
  • Are you using an emulator? if so, try it on a physical device or make sure the emulator is connected to the internet. for more information https://stackoverflow.com/questions/38418998/react-native-fetch-network-request-failed – Abdulmuhaymin Mar 06 '22 at 21:26
  • 1
    I am running this on a physical device. I should also add that the API call gets a response if I omit the "file" field on formData, so it's not an intrinsic problem with connecting via fetch() – Theone Mar 06 '22 at 22:09

0 Answers0