Created
September 29, 2021 12:41
-
-
Save bewarusman/5dc4846af0e1f882ae28cdb553d1100e to your computer and use it in GitHub Desktop.
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
| import { RecoilRoot, atom, useRecoilState, useRecoilValue } from "recoil"; | |
| const usersState = atom({ | |
| key: "usersState", | |
| default: [] | |
| }); | |
| const loadingState = atom({ | |
| key: "loadingState", | |
| default: false | |
| }); | |
| function FetchUsersList() { | |
| const [, setUsers] = useRecoilState(usersState); | |
| const [, setLoading] = useRecoilState(loadingState); | |
| function handleClick() { | |
| setLoading(true); | |
| fetch("https://jsonplaceholder.typicode.com/users") | |
| .then((res) => res.json()) | |
| .then((data) => { | |
| setUsers(data); | |
| setLoading(false); | |
| }); | |
| } | |
| return <button onClick={handleClick}>Refresh</button>; | |
| } | |
| function UsersList() { | |
| const users = useRecoilValue(usersState); | |
| const loading = useRecoilValue(loadingState); | |
| if (loading) { | |
| return ( | |
| <div> | |
| <p>Loading....</p> | |
| </div> | |
| ); | |
| } | |
| return ( | |
| <div> | |
| <p>List of users: {users.length}</p> | |
| </div> | |
| ); | |
| } | |
| export default function RecoilDemo() { | |
| return ( | |
| <RecoilRoot> | |
| <FetchUsersList /> | |
| <UsersList /> | |
| </RecoilRoot> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment