UNPKG

@tixae-labs/typesaurus-react

Version:

React Hooks for Typesaurus, type-safe Firestore ODM, MAINTAINED BY TIXAE LABS

39 lines (38 loc) 1.32 kB
"use strict"; exports.useWrite = useWrite; var _index = require("../adapter/index.js"); function useWrite(docRef) { const [loading, setLoading] = (0, _index.useState)(false); const [error, setError] = (0, _index.useState)(undefined); const write = (0, _index.useCallback)(data => { setLoading(true); setError(undefined); return new Promise((resolve, reject) => { const executeWrite = async () => { try { let result; console.log(`input doc ref? `, docRef); if (typeof docRef === 'object' && docRef !== null) { if ('set' in docRef && typeof docRef.set === 'function') { result = await docRef.set(data); } else if ('update' in docRef && typeof docRef.update === 'function') { result = await docRef.update(data); } else { throw new Error('Document reference does not support writing operations'); } } else { throw new Error('Invalid document reference'); } setLoading(false); resolve(result); } catch (err) { setLoading(false); setError(err); reject(err); } }; executeWrite(); }); }, [docRef, setLoading, setError]); return [write, loading, error]; }