A React Query-like data fetching and caching library for vanilla JavaScript/TypeScript applications.
- 📡 Async data fetching with automatic caching
- 🔄 Request deduplication and refetching
- ⚙️ Configurable retry logic
- 🪝 Rich lifecycle callbacks
- 🧠 Intelligent cache invalidation
- 🔄 Automatic refetching (on window focus, interval)
- 📝 TypeScript support
- 🔄 No dependencies
npm install @nugrhrizki/vanilla-query
or
pnpm add @nugrhrizki/vanilla-query
import { VanillaQuery } from '@nugrhrizki/vanilla-query'
// Create an instance
const queryClient = new VanillaQuery()
// Fetch and cache data
const usersQuery = queryClient.useQuery('users', async () => {
const response = await fetch('https://api.example.com/users')
return response.json()
})
// Subscribe to state changes
const unsubscribe = usersQuery.subscribe((state) => {
if (state.isLoading) {
console.log('Loading users...')
} else if (state.isError) {
console.error('Failed to load users:', state.error)
} else if (state.isSuccess) {
console.log('Users loaded:', state.data)
}
})
// Manual refetch
button.addEventListener('click', () => {
usersQuery.refetch()
})
// Cleanup subscription when done
// unsubscribe();
The main class that provides all functionality.
const queryClient = new VanillaQuery()
Creates a query instance for fetching and caching data.
queryKey
: Unique string identifier for the queryqueryFn
: Async function that fetches the dataoptions
: Configuration options
const query = queryClient.useQuery('users', fetchUsers, {
staleTime: 60000,
cacheTime: 300000,
retry: 3,
})
Creates a mutation instance for updating data.
const mutation = queryClient.useMutation(createUser, {
onSuccess: (data) => {
queryClient.invalidateQuery('users')
},
})
// Use the mutation
mutation.mutate({ name: 'John Doe' })
prefetchQuery(queryKey, queryFn, options)
: Pre-fetch and cache datagetQueryData(queryKey)
: Get cached data directlysetQueryData(queryKey, data)
: Manually update cached dataremoveQueryData(queryKey)
: Remove data from cacheclear()
: Clear all cached data and stop active queries
We welcome contributions! Please read our Contributing Guide before submitting pull requests.
By participating in this project, you agree to abide by our Code of Conduct.