Last active
April 13, 2022 11:44
-
-
Save iuliaL/e86229cb81a5ccec70b2eb5ec9d45504 to your computer and use it in GitHub Desktop.
two-way databinding with Jotai atoms
This file contains hidden or 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
/* | |
* 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