UNPKG

@hydevs/hypb

Version:

<img src="https://github.com/Hydevs-Corp/Hypb/blob/9308ab4c17196e5c0083c983a528326fd2cba867/.github/assets/banner.png" alt="usehooks-ts banner" align="center" />

59 lines (58 loc) 2.3 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { useEffect, useState } from 'react'; import { Hypb } from '../functions/pocketbase'; import { unsubcribe } from '../functions/unsubcribe'; export function useRecord(collection, recordId, params = { defaultValue: undefined, realtime: false, }) { const [record, setRecord] = useState(params.defaultValue); const [loading, setLoading] = useState(true); const getRecord = () => __awaiter(this, void 0, void 0, function* () { if (!recordId) return; setLoading(true); try { if (!recordId) throw new Error("Aucun identifiant n'a été donné"); const list = yield Hypb.pb .collection(collection) .getOne(recordId, params.queryParams); setRecord(list); } catch (e) { if (params.onNotFound && (yield params.onNotFound())) yield getRecord(); } finally { setLoading(false); } }); const [deleted, isDeleted] = useState(false); useEffect(() => { getRecord(); let unsub; if (params.realtime && recordId) unsub = Hypb.pb .collection(collection) .subscribe(recordId, (e) => { if (e.action === 'update') setRecord(e.record); if (e.action === 'delete') { isDeleted(true); } }); return () => { unsubcribe(unsub); }; }, [recordId]); return { record, invalidate: getRecord, loading, deleted }; }