Usage
import { useListState } from '@kivora/react';
function TodoList() {
const [items, handlers] = useListState(['Buy milk', 'Walk dog']);
return (
<div>
{items.map((item, index) => (
<div key={index}>
<span>{item}</span>
<button onClick={() => handlers.remove(index)}>Remove</button>
</div>
))}
<button onClick={() => handlers.append('New task')}>Add Task</button>
</div>
);
}
Parameters
Initial array value
Return Value
Returns a tuple with the current array and an object of mutation handlers:Current array state
Mutation handlers
Show properties
Show properties
Add items to the end of the list
Add items to the beginning of the list
Insert items at a specific index
Remove items at the specified indices
Move an item from one index to another
Swap two items by their indices
Replace the entire list
Update a specific item by index
Apply a transformation function to the entire list
Filter the list using a predicate function
Examples
Managing a Todo List
const [todos, handlers] = useListState([
{ id: 1, text: 'Learn React', done: false },
{ id: 2, text: 'Build app', done: false }
]);
// Add new todo
handlers.append({ id: 3, text: 'Deploy', done: false });
// Remove completed todos
handlers.filter((todo) => !todo.done);
// Mark todo as done
handlers.setItem(0, { ...todos[0], done: true });
Drag and Drop Reordering
const [items, handlers] = useListState(['A', 'B', 'C', 'D']);
const onDragEnd = (result) => {
if (!result.destination) return;
handlers.reorder(result.source.index, result.destination.index);
};
Form Fields Array
const [fields, handlers] = useListState([{ name: '', email: '' }]);
return (
<div>
{fields.map((field, index) => (
<div key={index}>
<input
value={field.name}
onChange={(e) => handlers.setItem(index, { ...field, name: e.target.value })}
/>
<button onClick={() => handlers.remove(index)}>Remove</button>
</div>
))}
<button onClick={() => handlers.append({ name: '', email: '' })}>
Add Field
</button>
</div>
);
Insert at Position
const [list, handlers] = useListState([1, 2, 4, 5]);
// Insert 3 at index 2
handlers.insert(2, 3); // [1, 2, 3, 4, 5]