Skip to content

Instantly share code, notes, and snippets.

@iuliaL
Last active April 13, 2022 11:44
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 iuliaL/e86229cb81a5ccec70b2eb5ec9d45504 to your computer and use it in GitHub Desktop.
Save iuliaL/e86229cb81a5ccec70b2eb5ec9d45504 to your computer and use it in GitHub Desktop.
two-way databinding with Jotai atoms
/*
* This atom, when you set its value, triggers the custom write function we provide,
* and can modify the atoms it relies on. It's basically two-way data binding.
*/
import { atom, useAtom } from 'jotai';
const priceAtom = atom(10);
const priceModifier = atom(
(get) => get(priceAtom) * 2, // this is called derived atom
(get, set) => {
set(priceAtom, get(priceAtom) / 3);
// you can set as many atoms as you want at the same time
}
);
export default function MainPage(): React.ReactElement {
const [price] = useAtom(priceAtom);
const [myDoubledPrice, setPriceToOneThird] = useAtom(priceModifier);
return (
<div>
<div>price: {price}</div>
<div>doubled price: {myDoubledPrice}</div>
<button onClick={() => setPriceToOneThird()}>Set price to 1/3</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment