@tixae-labs/typesaurus-react
Version:
React Hooks for Typesaurus, type-safe Firestore ODM, MAINTAINED BY TIXAE LABS
36 lines • 1.26 kB
JavaScript
import { useState, useCallback } from "../adapter/index.mjs";
export function useWrite(docRef) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(undefined);
const write = 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];
}