1

I need to get the extension of an image from my library and set this value to a variable, because I need this variable to make a API POST later. I am using Image Picker library to select the image, and also a function to know what is the extension of my image. The problem is that when I select an image and set the value in my variable 'extension', it is set wrongly and late. After I select the image again, it works. I don't know if it is a problem with async.

I attached the code of both functions. Thanks!

let extension = '';

const RENAPER_DNI_FRONT = ({ navigation }) => {

const [image_base64, setImageBase64] = useState('');
const [image, setImage] = useState("https://via.placeholder.com/200x100")

function base64FileHeaderMapper(fileBase64) {
  
    let fileHeader = new Map();

    //get the first 3 char of base64
    fileHeader.set("/9j", "JPG")
    fileHeader.set("iVB", "PNG")
    fileHeader.set("Qk0", "BMP")
    fileHeader.set("SUk", "TIFF")
    fileHeader.set("JVB", "PDF")
    fileHeader.set("UEs", "OFD")

    let res = ""

    fileHeader.forEach((v, k) => {
        if (k == fileBase64.substr(0, 3)) {
            res = v
        }
    })

    //if file is not supported
    if (res == "") {
        res = "unknown file"
    }

    //return map value
    return res;
}


//  //ImagePicker place holder
 const selectImage = async () => {
    const options = {
        title : 'Select an image',
        storageOptions: {
            skipBackup: true,
            path: 'images'
        },
        includeBase64: true,
    }
    
    ImagePicker.launchImageLibrary(options, response =>{
       
      if (response.errorCode) {
          console.log(response.errorMessage)
      }
      else if (response.didCancel)
      {
          console.log("the user cancel the selection")
      }
      else{

          const uriLibrary = response.assets[0].uri
          
          setImage(uriLibrary)
          
         
         //Set image in base 64 
          setImageBase64(response.assets[0].base64)          
          extension = base64FileHeaderMapper(image_base64);
          console.log('This is my extension ' + extension);
      }
    })
}
  • setting state is asynchronous, it's possible its not getting set in time before you use it. Do you really need `setImageBase64` state? why not just pass the response directly to the function like `extension = base64FileHeaderMapper(response.assets[0].base64);`? – Andrew Lohr Jan 18 '22 at 21:56
  • if `setImageBase64` needs to be handled using state then you can read through https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – Andrew Lohr Jan 18 '22 at 21:59

0 Answers0