Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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