UNPKG

@pubflow/nextjs

Version:

Next.js adapter for Pubflow framework

87 lines (86 loc) 2.81 kB
"use strict"; /** * Bridge Mutation Hook for Next.js * * Provides a hook for mutating data using Bridge API */ Object.defineProperty(exports, "__esModule", { value: true }); exports.useBridgeMutation = useBridgeMutation; const react_1 = require("react"); const swr_1 = require("swr"); /** * Hook for mutating data using Bridge API * * @param service Bridge API service * @param type Mutation type * @param defaultOptions Default mutation options * @returns Mutation result */ function useBridgeMutation(service, type, defaultOptions = {}) { // State const [isLoading, setIsLoading] = (0, react_1.useState)(false); const [error, setError] = (0, react_1.useState)(null); // SWR config for cache invalidation const { mutate: mutateCache } = (0, swr_1.useSWRConfig)(); // Define mutate function const mutate = (0, react_1.useCallback)(async (params, options) => { // Merge options const mergedOptions = { ...defaultOptions, ...options }; // Reset error setError(null); // Set loading setIsLoading(true); try { let result; // Perform mutation based on type switch (type) { case 'create': result = await service.create(params); break; case 'update': const { id, data } = params; result = await service.update(id, data); break; case 'delete': await service.delete(params); result = undefined; break; default: throw new Error(`Invalid mutation type: ${type}`); } // Invalidate queries if configured if (mergedOptions.invalidateQueries !== false) { await mutateCache((key) => typeof key === 'string' && key.includes(JSON.stringify({ service })), undefined, { revalidate: true }); } // Call success callback if (mergedOptions.onSuccess) { mergedOptions.onSuccess(result); } return result; } catch (err) { // Set error setError(err); // Call error callback if (mergedOptions.onError) { mergedOptions.onError(err); } throw err; } finally { // Reset loading setIsLoading(false); } }, [service, type, defaultOptions, mutateCache]); // Define reset function const reset = (0, react_1.useCallback)(() => { setError(null); setIsLoading(false); }, []); return { mutate, isLoading, error, reset }; }