Skip to content

Instantly share code, notes, and snippets.

@ourmaninamsterdam
Created June 23, 2021 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ourmaninamsterdam/ab37a6ab464d0dbcebd311a8d7ce0241 to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/ab37a6ab464d0dbcebd311a8d7ce0241 to your computer and use it in GitHub Desktop.
useDirectorySync - syncs React Native directories (using react-native-fs) on appState change
import { useState } from 'react';
import useAppState from 'react-native-appstate-hook';
import RNFS from 'react-native-fs';
async function copyDir(source: string, destination: string) {
const fileChangeLog: string[] = [];
await copyDirRecursive(source, destination, fileChangeLog);
return fileChangeLog;
}
async function copyDirRecursive(source: string, destination: string, fileChangeLog: string[]) {
const items = await RNFS.readDir(source);
await RNFS.mkdir(destination);
await items.forEach(async (item) => {
if (item.isFile()) {
const destinationFile = `${destination}/${item.name}`;
const fileExists = await RNFS.exists(destinationFile);
if (fileExists) {
const sourceFileHash = await RNFS.hash(item.path, 'md5');
const destinationFileHash = await RNFS.hash(destinationFile, 'md5');
if (sourceFileHash === destinationFileHash) return;
RNFS.unlink(destinationFile);
return;
}
await RNFS.copyFile(item.path, destinationFile);
fileChangeLog.push(destinationFile);
} else {
const sourceDir = `${source}/${item.name}`;
const destinationDir = `${destination}/${item.name}`;
await copyDirRecursive(sourceDir, destinationDir, fileChangeLog);
}
});
}
const useDirectorySync = (directorySource: string, directoryDestination: string) => {
const [directoryPath, setDirectoryPath] = useState('');
useAppState({
onForeground: async () => {
const filesChanged = await copyDir(directorySource, directoryDestination);
if (filesChanged.length) console.info('FilesChanged', filesChanged);
setDirectoryPath(directoryDestination);
},
});
return directoryPath;
};
export default useDirectorySync;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment