Skip to content

Commit

Permalink
[use-queue] Handle limit changes (#16)
Browse files Browse the repository at this point in the history
* Allow limit to be changed

* docs(changeset): [use-queue] handle limit changes
  • Loading branch information
the-dijkstra committed Aug 7, 2024
1 parent 5890ee6 commit d49cb19
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/itchy-actors-call.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@codiume/hooks": patch
---

[use-queue] handle limit changes
11 changes: 11 additions & 0 deletions src/use-queue/use-queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,15 @@ describe('useQueue', () => {
expect(dequeuedItem).toBeUndefined();
expect(result.current[0]).toEqual({ active: [], queue: [] });
});

it('should handle limit changes', () => {
const { result, rerender } = renderHook(
({ limit }: { limit: number }) => useQueue<number>([1, 2, 3, 4], limit),
{ initialProps: { limit: 2 } }
);
expect(result.current[0]).toEqual({ active: [1, 2], queue: [3, 4] });

rerender({ limit: 3 });
expect(result.current[0]).toEqual({ active: [1, 2, 3], queue: [4] });
});
});
12 changes: 11 additions & 1 deletion src/use-queue/use-queue.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';

type QueueState<T> = {
active: T[];
Expand All @@ -22,6 +22,16 @@ export function useQueue<T>(
queue: initialValues.slice(limit)
}));

useEffect(() => {
setState((current) => {
const newState = [...current.active, ...current.queue];
return {
active: newState.slice(0, limit),
queue: newState.slice(limit)
};
});
}, [limit]);

const enqueue = (item: T) =>
setState((current) => {
const newState = [...current.active, ...current.queue, item];
Expand Down

0 comments on commit d49cb19

Please sign in to comment.