Skip to content

Instantly share code, notes, and snippets.

@ksimons
Created October 12, 2022 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksimons/09f7b02c149f86fd1efb70fc5838a662 to your computer and use it in GitHub Desktop.
Save ksimons/09f7b02c149f86fd1efb70fc5838a662 to your computer and use it in GitHub Desktop.
Using Recoil.js transactions
interface BulkItemCreator {
create(items: Array<{ id: string; name: string }>): void;
}
export function useBulkCreateExample() {
return useRecoilCallback(
({ transact_UNSTABLE }) =>
(callback: (creator: BulkItemCreator) => void) => {
transact_UNSTABLE(({ set, get }) => {
callback({
create(items) {
// all of these set() calls happen in one atomic operation
for (const item of items) {
set(itemAtomFamily(item.id), item);
}
// you can use get() here, but only for atoms, not selectors
},
});
});
}
);
}
// Simple example of using a transaction
function SomeComponent() {
const bulkCreate = useBulkCreateExample();
const handleClick = React.useCallback(() => {
bulkCreate((creator) => {
creator.create([
{ id: '123', name: 'Bob' },
{ id: '234', name: 'Susan' },
]);
});
}, []);
return <button onClick={handleClick}>Create</button>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment