useQueue
Manage a queue of items with automatic state limiting.
Import
import { useQueue } from '@tidbcloud/uikit'Usage
useQueue limits the number of items in the current state and places the rest in a queue. This is useful for scenarios like notification systems where you want to display a limited number of items.
import { useQueue } from '@tidbcloud/uikit'
const { state, queue, add, update, cleanQueue } = useQueue({
initialValues: [1],
limit: 2
})
// state -> [1], queue -> []
// When state.length is less than limit, items are added to state
add(2)
// state -> [1, 2], queue -> []
// When state.length equals limit, items are added to queue
add(3, 4, 5, 6)
// state -> [1, 2], queue -> [3, 4, 5, 6]
// Use update to modify items
update((values) => values.map((item) => item * 3))
// state -> [3, 6], queue -> [9, 12, 15, 18]
// Items added/removed in update are distributed according to limit
update((values) => values.filter((item) => item % 2))
// state -> [3, 9], queue -> [15]
// Remove all items from queue
cleanQueue()
// state -> [3, 9], queue -> []
// Remove all items
update(() => [])
// state -> [], queue -> []Options
initialValues– optional initial values, divided between state and queue according to limitlimit– maximum number of items that state can include
Set Item Type
import { useQueue } from '@tidbcloud/uikit'
// Type inferred from initialValues
const q = useQueue({
limit: 2,
initialValues: [{ name: 'Bob', id: 1 }]
})
// Explicit type for empty initial values
const q2 = useQueue<{ name: string; id: number }>({
limit: 2,
initialValues: []
})Definition
interface UseQueueOptions<T> {
initialValues?: T[]
limit: number
}
interface UseQueueReturnValue<T> {
queue: T[]
state: T[]
add: (...items: T[]) => void
update: (fn: (state: T[]) => T[]) => void
cleanQueue: () => void
}
function useQueue<T>(options: UseQueueOptions<T>): UseQueueReturnValue<T>