How to perform a two callback functionality?

178 Views Asked by At

I am using the cloudinary api with REACT/AXIOS and was wondering how I could pull data before the axios call and also after. My problem I am having is that if I use one callback I can only put the one or the other data. So is it possible to use two callbacks and if so how would you do so?

Or should I go about this a different way?

What I want is to pull the progression of the upload out and be able to store that value to the state. My only problem is that I am not sure of the correct way to do this? I need to do it inside the onUploadProgress fucntion.

Here is the code:

Function in component:

uploadImage(files) {
    const image = files[0];

    const cloudName = 'hyszj0vmt';
    const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;

    const apiSecret = '***********';
    const uploadPreset = '**************';
    const timestamp = Date.now() / 1000;
    const paramStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}${apiSecret}`;
    const signature = sha1(paramStr);
    const params = {
      api_key: '*******',
      timestamp: timestamp,
      upload_preset: uploadPreset,
      signature: signature
    };

    APIManager.upload(url, image, params, (err, response) => {
      if (err) {
        console.log(`UPLOAD ERROR: ${err}`);
        return;
      }

      const imageUrl = response['secure_url'];
      let updatedProfile = Object.assign({}, this.state.updated);
      updatedProfile['image'] = imageUrl;

      this.setState({
        updated: updatedProfile
      });
    });
  }

APIManager function:

upload: (endpoint, file, params, callback) => {
    let fd = new FormData();

    fd.append('file', file);
    Object.keys(params).forEach(key => {
      fd.append(key, params[key]);
    });

    const config = {
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      onUploadProgress: progressEvent => {
        const progress = Math.round(
          progressEvent.loaded * 100.0 / progressEvent.total
        );

        console.log(progress + '%');
      }
    };

    axios
      .post(endpoint, fd, config)
      .then(response => {
        const { data } = response;
        callback(null, data);
      })
      .catch(err => {
        callback(err, null);
      });
  }
};
1

There are 1 best solutions below

3
On BEST ANSWER

How about this?

upload: (endpoint, file, params, callback, callbackProgress) => {
    ...

    const config = {
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      onUploadProgress: progressEvent => {
        const progress = Math.round(
          progressEvent.loaded * 100.0 / progressEvent.total
        );
        callbackProgress(progress);
      }
    };

    ...
});

Usage:

APIManager.upload(url, image, params, (err, response) => {
  ...
}, (progress) => {
    console.log(progress);
});