JavaScript - Passing data to callback with predefined parameters

179 Views Asked by At

If anyone could help me out on this I would be extremely grateful. I think there is probably a simple solution out there, but I can't work it out and it's extremely frustrating.

I'm using Expo to develop a React Native app. Their SDK has a 'downloadResumable' feature that allows users to download files.

The callback function, which provides download progress information, gets an object with 'totalBytesWritten' and 'totalBytesExpectedToWrite' props automatically passed to it.

Is there any way I could pass in the 'songId' argument that I passed to createDownloadResumable in to the callback function, so that the callback doesn't need to reference the outer '_id' variable?

Thanks in advance to anyone that can help me out with this!

const { _id } = song;

const callback = ({ totalBytesWritten, totalBytesExpectedToWrite }) => dispatch(updateDownloadProgress(
  _id,
  totalBytesWritten,
  totalBytesExpectedToWrite
));

const createDownloadResumable = songId => FileSystem.createDownloadResumable(
  link,
  FileSystem.documentDirectory + `${songId}.mp3`,
  {},
  callback,
);

const downloadResumable = createDownloadResumable(_id);
1

There are 1 best solutions below

1
On BEST ANSWER

You should be able to do this by creating the callback within a closure like this:

const { _id } = song;

const generateCallback = (songId) => {
  return ({ totalBytesWritten, totalBytesExpectedToWrite }) => dispatch(updateDownloadProgress(
    songId,
    totalBytesWritten,
    totalBytesExpectedToWrite
  ));
}

const createDownloadResumable = (songId) => FileSystem.createDownloadResumable(
  link,
  FileSystem.documentDirectory + `${songId}.mp3`,
  {},
  generateCallback(songId),
);

const downloadResumable = createDownloadResumable(_id);