Expo React native fetch requests twice

import React,  { useState } from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
import * as FileSystem from 'expo-file-system';

export default function App() {



  let data = new FormData();


 

let url="https://uploadfilesserver.eugenevolkov.repl.co/upload"

  

data.append("content",{type:'image/jpeg', uri:'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/201a148e3d40baa81d8ef06e316b5ca2', name:'ball.jpg'} )






function upload(){

fetch(url, {
  method: "post",
   headers: {
         "Content-Type": "multipart/form-data",
    },
  body: data,
})

.then(res => {res.json()

// console.log('res',res)
}
)
  .then(final => {

    console.log(
      "Success")}
     
    )
    
  //    .catch(err => {
  //   console.error("error uploading images: ", err);
  // });

}


upload()

return ( Image to upload <Image source={require('./ball_1.jpg')}/> ); }

i am new to react native. The fecth always results in two uploads (two POST reqests). There is no OPTIONS request. In the backend (Django) upload folder there are always 2 'ball.jpg' files. The same issue happens after building app.

Try to use then() only one time :

function upload(){
      fetch(url, {
                method: "post",
                headers: {
                        "Content-Type": "multipart/form-data",
                },
                body: data,
      })
      .then(res => {
           res.json()
           console.log("Success")
       })

 }

For the React Native IOS platform, you must send a URL without the 'file://' prefix. I believe it could be the same as Expo. It can be used when used with a file or picture picked from your mobile.

Defining function as async fixed it.

    async function upload(){
    
           await fetch(url, {
            
                    method: "post",
                    headers: {
                            "Content-Type": "multipart/form-data",
                    },
                    body: data,
                          })
          .then(res => {
               res.json()
               console.log("Success")
    
           })       
     }

upload()
Back to Top