Skip to content

Commit 7551fdf

Browse files
lgordeyalexkrolick
andauthored
Add ajax with hooks example (#2803)
* Add ajax with hooks example * Add comment about empty deps in useEffect hook * grammar Co-authored-by: Alex Krolick <[email protected]>
1 parent 6ff9c4b commit 7551fdf

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

content/docs/faq-ajax.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,50 @@ class MyComponent extends React.Component {
8282
}
8383
}
8484
```
85+
86+
Here is the equivalent with [Hooks](https://reactjs.org/docs/hooks-intro.html):
87+
88+
```js
89+
function MyComponent() {
90+
const [error, setError] = useState(null);
91+
const [isLoaded, setIsLoaded] = useState(false);
92+
const [items, setItems] = useState([]);
93+
94+
// Note: the empty deps array [] means
95+
// this useEffect will run once
96+
// similar to componentDidMount()
97+
useEffect(() => {
98+
fetch("https://api.example.com/items")
99+
.then(res => res.json())
100+
.then(
101+
(result) => {
102+
setIsLoaded(true);
103+
setItems(result.items);
104+
},
105+
// Note: it's important to handle errors here
106+
// instead of a catch() block so that we don't swallow
107+
// exceptions from actual bugs in components.
108+
(error) => {
109+
setIsLoaded(true);
110+
setError(error);
111+
}
112+
)
113+
}, [])
114+
115+
if (error) {
116+
return <div>Error: {error.message}</div>;
117+
} else if (!isLoaded) {
118+
return <div>Loading...</div>;
119+
} else {
120+
return (
121+
<ul>
122+
{items.map(item => (
123+
<li key={item.name}>
124+
{item.name} {item.price}
125+
</li>
126+
))}
127+
</ul>
128+
);
129+
}
130+
}
131+
```

0 commit comments

Comments
 (0)