~repos /atoms-state

#js#react#flux

git clone https://pyrossh.dev/repos/atoms-state.git

Simple State management for react


c056c550 pyros2097

4 years ago
add async example
Files changed (1) hide show
  1. README.md +40 -0
README.md CHANGED
@@ -7,6 +7,7 @@ A simple statemanagement library for react.
7
7
  `npm i @pyros2097/atoms`
8
8
 
9
9
  ## Usage
10
+
10
11
  ```js
11
12
  import React from 'react';
12
13
  import ReactDOM from 'react-dom';
@@ -39,3 +40,42 @@ const Counter = () => {
39
40
 
40
41
  ReactDOM.render(<Counter />, document.getElementById('root'));
41
42
  ```
43
+
44
+ ## Async
45
+
46
+ ```js
47
+ import React, { Suspense } from 'react';
48
+ import ReactDOM from 'react-dom';
49
+ import { asyncAtom, useAsyncAtom } from '@pyros2097/atoms';
50
+
51
+ const todoAtom = asyncAtom(async ({ id }) => {
52
+ const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
53
+ return await res.json();
54
+ });
55
+
56
+ const completeTodo = () => {
57
+ todoAtom.update(todo => ({ ...todo, completed: !todo.completed }));
58
+ };
59
+
60
+ const Counter = () => {
61
+ const todo = useAsyncAtom(todoAtom, { id: 1 });
62
+
63
+ return (
64
+ <div>
65
+ <p>id: {todo.id}</p>
66
+ <p>userId: {todo.userId}</p>
67
+ <p>title: {todo.title}</p>
68
+ <p>completed: {todo.completed}</p>
69
+ <p>Sum: {sum}</p>
70
+ <button onClick={completeTodo}>Toggle Complete</button>
71
+ </div>
72
+ );
73
+ };
74
+
75
+ ReactDOM.render(
76
+ <Suspense fallback={<div>Loading</div>}>
77
+ <Counter />
78
+ </Suspense>,
79
+ document.getElementById('root')
80
+ );
81
+ ```