I am trying to store a file locally, but I don't have the media URL. I have an API that provides an authorization token. Then, I utilize the react-native-fs library in our React Native project. This library also offers API calling features.
import RNFS from "react-native-fs";
export const appDirectory = `${RNFS.DocumentDirectoryPath}/EasyMd`;
export async function createAppDirectory() {
try {
const directoryExists = await RNFS.exists(appDirectory);
if (!directoryExists) {
await RNFS.mkdir(appDirectory);
}
} catch (error) {
console.log("Error while creating app directory: ", error);
}
}
async function getPdfFilePrescriptionDetails() {
try {
setPdfLoading(true);
await createAppDirectory();
const path = `${appDirectory}/prescription.pdf`;
try {
const downloadOptions = {
fromUrl: `${Development.BASE_URL}${Api.GET_PRESCRIPTION_API}/${id}/export`,
toFile: `${path}`,
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
};
await Promise.all([RNFS.downloadFile(downloadOptions)]);
setPdfUri({ url: `file://${path}` });
} catch (error) {
console.log("Error saving PDF:", error);
} finally {
setPdfLoading(false);
}
} catch (e) {
console.log("Errro v", e);
}
}
This is my solution. If you have another best solution, please feel free to add your comment.