Introduction

The current version of the To-Do List demo app implements a PhotoAttachmentQueue class which enables photo attachments (specifially a jpeg) to be synced. This tutorial will guide you on the changes needed to support PDF attachments.

An overview of the required changes are:

  1. Update the app schema by adding a pdf_id column to the todos table to link a pdf to a to-do item.
  2. Add a PdfAttachmentQueue class
  3. Initialize the PdfAttachmentQueue class

The following pre-requisites are required to complete this tutorial:

Steps

Usage Example

The newly created attachmentPdfQueue can now be used in a component by using the useSystem hook created in step-3 above

The code snippet below illustrates how a pdf could be saved when pressing a button. It uses a DocumentPicker UI component to allow the user to select a pdf. When the button is pressed, savePdf is called.

The saveAttachment method in the PdfAttachmentQueue class expects a base64 encoded string. We can therefore use react-native-fs to read the file and return the base64 encoded string which is passed to saveAttachment.

If your use-case generates a pdf file, ensure that you return a base64 encoded string.

import DocumentPicker from 'react-native-document-picker';
import RNFS from 'react-native-fs';

// Within some component

// useSystem is imported from system.ts 
const system = useSystem();

const savePdf = async (id: string) => {  
  if (system.attachmentPdfQueue) {  
    const res = await DocumentPicker.pick({  
      type: [DocumentPicker.types.pdf]  
    });  
  
    console.log(`Selected PDF: ${res[0].uri}`);
    const base64 = await RNFS.readFile(res[0].uri, 'base64');  
    const { id: attachmentId } = await system.attachmentPdfQueue.saveAttachment(base64);  
  
    await system.powersync.execute(`UPDATE ${TODO_TABLE} SET pdf_id = ? WHERE id = ?`, [attachmentId, id]);  
  }  
};

<Button title="Select PDF" onPress={savePdf} />

Notes

Although this tutorial adds a new pdf_id column, the approach you should take strongly depends on your requirements.

An alternative approach could be to replace the photo_id with an attachment_id and have one AttachmentQueue class that handles all attachment types instead of having a class per attachment type.