/**
* useMemoryStack Hook
* Access the MemoryStack client and context from any component
*/
import { useContext } from 'react';
import { MemoryStackContext, MemoryStackContextValue } from '../context/MemoryStackContext';
import { MemoryStackClient } from '../client';
/**
* Hook to access the MemoryStack client and context
*
* @example
* ```tsx
* function MyComponent() {
* const { client, isOnline, pendingOperations, syncPending } = useMemoryStack();
*
* const handleAddMemory = async () => {
* if (!client) return;
* await client.add("User prefers dark mode");
* };
*
* return (
*
* Online: {isOnline ? 'Yes' : 'No'}
* Pending: {pendingOperations}
*
*
* );
* }
* ```
*/
export function useMemoryStack(): MemoryStackContextValue {
const context = useContext(MemoryStackContext);
if (!context.isInitialized && context.client === null) {
console.warn(
'[MemoryStack] useMemoryStack must be used within a MemoryStackProvider. ' +
'Make sure your app is wrapped with .'
);
}
return context;
}
/**
* Hook to access just the MemoryStack client
* Throws an error if used outside of provider
*
* @example
* ```tsx
* function MyComponent() {
* const client = useMemoryStackClient();
*
* const handleSearch = async () => {
* const results = await client.search("user preferences");
* console.log(results);
* };
*
* return ;
* }
* ```
*/
export function useMemoryStackClient(): MemoryStackClient {
const { client, isInitialized } = useContext(MemoryStackContext);
if (!client) {
if (!isInitialized) {
throw new Error(
'[MemoryStack] useMemoryStackClient must be used within a MemoryStackProvider. ' +
'Make sure your app is wrapped with .'
);
}
throw new Error('[MemoryStack] Client not initialized yet. Wait for isInitialized to be true.');
}
return client;
}
/**
* Hook to check if device is online
*
* @example
* ```tsx
* function OnlineIndicator() {
* const isOnline = useIsOnline();
* return {isOnline ? '🟢' : '🔴'};
* }
* ```
*/
export function useIsOnline(): boolean {
const { isOnline } = useContext(MemoryStackContext);
return isOnline;
}
/**
* Hook to get pending operations count
*
* @example
* ```tsx
* function PendingBadge() {
* const pendingCount = usePendingOperations();
* if (pendingCount === 0) return null;
* return ;
* }
* ```
*/
export function usePendingOperations(): number {
const { pendingOperations } = useContext(MemoryStackContext);
return pendingOperations;
}
export default useMemoryStack;