mirror of
https://github.com/reactjs/react.dev.git
synced 2026-02-24 04:33:10 +00:00
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 <alexkrolick@users.noreply.github.com>
This commit is contained in:
@@ -82,3 +82,50 @@ class MyComponent extends React.Component {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Here is the equivalent with [Hooks](https://reactjs.org/docs/hooks-intro.html):
|
||||
|
||||
```js
|
||||
function MyComponent() {
|
||||
const [error, setError] = useState(null);
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
const [items, setItems] = useState([]);
|
||||
|
||||
// Note: the empty deps array [] means
|
||||
// this useEffect will run once
|
||||
// similar to componentDidMount()
|
||||
useEffect(() => {
|
||||
fetch("https://api.example.com/items")
|
||||
.then(res => res.json())
|
||||
.then(
|
||||
(result) => {
|
||||
setIsLoaded(true);
|
||||
setItems(result.items);
|
||||
},
|
||||
// Note: it's important to handle errors here
|
||||
// instead of a catch() block so that we don't swallow
|
||||
// exceptions from actual bugs in components.
|
||||
(error) => {
|
||||
setIsLoaded(true);
|
||||
setError(error);
|
||||
}
|
||||
)
|
||||
}, [])
|
||||
|
||||
if (error) {
|
||||
return <div>Error: {error.message}</div>;
|
||||
} else if (!isLoaded) {
|
||||
return <div>Loading...</div>;
|
||||
} else {
|
||||
return (
|
||||
<ul>
|
||||
{items.map(item => (
|
||||
<li key={item.name}>
|
||||
{item.name} {item.price}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user