jquery-pro-query
v1.0.0
Published
Smart async data fetching, automatic caching, request deduplication, and SWR for jQuery.
Maintainers
Readme
jquery-pro-query 🌐 v1.1.0
Smart Async Data Fetching, Automatic Caching, Request Deduplication, SWR, Optimistic UI, & Infinite Queries for jQuery.
Bring modern server-state management (like TanStack/React Query v5 and SWR) to your legacy jQuery applications. Stop writing repetitive $.ajax() boilerplate and start building fast, cached, auto-updating web applications with zero backend changes.
Features in v1.1.0 🚀
- ⚡ Optimistic UI Updates & Cache Rollback: Instantly update the UI before the network request finishes, with automatic rollback if the server fails.
- ♾️ Infinite Scrolling & Paginated Queries (
$.infiniteQuery): Handle paginated feeds and "Load More" lists withfetchNextPage(),hasNextPage, andisFetchingNextPage. - 💾 Offline Cache Persistence (
$.queryClient.setPersistence): Persist query cache tolocalStorageorsessionStorageso pages load instantly offline. - 🔗 Conditional & Dependent Queries (
enabledflag): Execute queries conditionally (e.g. wait for a user ID signal before fetching user details). - 🔌 Native
jquery-signalsIntegration: Reactive Signals fordata,isLoading,isFetching,isError,isFetchingNextPage.
Quick Example
// Enable Offline Cache Persistence
$.queryClient.setPersistence({ key: 'app_query_cache', storage: 'local' });
// 1. Conditional Query (only runs when userId has a value)
const userDetails = $.query(['user', userIdSignal], () => $.get(`/api/user/${userIdSignal.value}`), {
enabled: () => Boolean(userIdSignal.value)
});
// 2. Infinite Query for Paginated Lists
const auditLogs = $.infiniteQuery('audit-logs', ({ pageParam = 1 }) => $.get(`/api/logs?page=${pageParam}`), {
initialPageParam: 1,
getNextPageParam: (lastPage, allPages) => lastPage.hasMore ? allPages.length + 1 : undefined
});
// 3. Optimistic UI Mutation with Rollback
const updateName = $.mutation((newName) => $.post('/api/user', { name: newName }), {
onMutate: async (newName) => {
const previousData = $.queryClient.getQueryData('user');
$.queryClient.setQueryData('user', { ...previousData, name: newName }); // 0ms UI Update!
return { previousData }; // Return rollback context
},
onError: (err, variables, context) => {
if (context?.previousData) {
$.queryClient.setQueryData('user', context.previousData); // Automatic Rollback!
}
}
});Core API Reference
$.query(queryKey, fetcherFn, [options])
Creates a managed async query instance.
Options:
enabled(boolean|function): Conditional execution. If false or evaluates to false, query will not run.staleTime(number): Time in ms before data is considered stale.cacheTime(number): Time in ms data stays in memory cache (default: 5 mins).refetchOnWindowFocus(boolean): Re-runs query when browser tab regains focus.retry(number): Retry attempts on failure.
$.infiniteQuery(queryKey, fetcherFn, [options])
Creates a managed paginated / infinite scrolling query instance.
Options:
initialPageParam: Initial page parameter (default:1).getNextPageParam(lastPage, allPages): Function determining the next page parameter or returningundefinedif no more pages exist.
Methods:
fetchNextPage(): Fetches the next page and appends it todata.pages.hasNextPage: Reactive signal/boolean indicating if more pages are available.isFetchingNextPage: Reactive signal/boolean indicating if a next page request is running.
$.mutation(mutationFn, [options])
Creates a managed async mutation instance.
Options:
onMutate(variables): Fired before mutation starts (ideal for Optimistic UI updates). Returns rollback context.onSuccess(data, variables, context): Fired when mutation succeeds.onError(error, variables, context): Fired when mutation fails (ideal for cache rollbacks).onSettled(data, error, variables, context): Fired on success or failure.
$.queryClient
Global cache and query controller.
$.queryClient.setPersistence({ key, storage, maxAge }): Enables persistent caching tolocalStorage/sessionStorage.$.queryClient.setQueryData(key, updaterOrValue): Manually updates or populates cached query data.$.queryClient.getQueryData(key): Retrieves cached data for a query key.$.queryClient.invalidateQueries(keyPattern): Marks matching queries stale and triggers background refetch.$.queryClient.prefetchQuery(key, fetcherFn): Fetches data ahead of time.
License
MIT
