Skip to main content

schema.Collection

Collections are entities but for Arrays or Values.

Collections implement the EntityInterface. By using the same lifecycle methods they give the same high performance and data integrity of Entity, but for Arrays or Values.

Usage

To describe a simple array of a singular entity type:

Fixtures
GET /todos
[{"id":"123","title":"Build Collections"},{"id":"456","title":"Add atomic creation"}]
POST /todos
response(body){return{id:(0,uuid__WEBPACK_IMPORTED_MODULE_8__/* ["default"] */ .Z)(),...body};}
api/Todo
export class Todo extends Entity {
id = '';
userId = 0;
title = '';
completed = false;
pk() {
return this.id;
}
static key = 'Todo';
}
export const getTodos = new RestEndpoint({
path: '/todos',
schema: new schema.Collection([Todo], {
argsKey: urlParams => ({ ...urlParams }),
}),
});
NewTodo
import { getTodos } from './api/Todo';
export default function NewTodo({ userId }: { userId?: number }) {
const ctrl = useController();
const handlePress = React.useCallback(
async (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
ctrl.fetch(getTodos.push, { title: e.currentTarget.value, userId });
e.currentTarget.value = '';
}
},
[ctrl],
);
return (
<div>
<input type="text" onKeyDown={handlePress} />
</div>
);
}
TodoList
import { getTodos } from './api/Todo';
import NewTodo from './NewTodo';
function TodoList() {
const todos = useSuspense(getTodos);
return (
<div>
{todos.map(todo => (
<div key={todo.pk()}>{todo.title}</div>
))}
<NewTodo />
</div>
);
}
render(<TodoList />);
Live Preview
Loading...
Store
    • {} 0 keys
      • {} 0 keys
        • {} 0 keys
          • {} 0 keys
            • {} 0 keys
              • 0