Created
October 12, 2022 12:11
-
-
Save ksimons/09f7b02c149f86fd1efb70fc5838a662 to your computer and use it in GitHub Desktop.
Using Recoil.js transactions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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