Skip to content

Commit b04cedc

Browse files
authored
Merge pull request #224 from adrian-burkhart/master
Update answer to question 303
2 parents cd0e5ef + b1875d8 commit b04cedc

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

README.md

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6402,25 +6402,20 @@ Learn to code and get hired with <a href="https://zerotomastery.io/?utm_source=g
64026402
64036403
303. ### How to fetch data with React Hooks?
64046404
6405-
The effect hook called `useEffect` is used to fetch the data with axios from the API and to set the data in the local state of the component with the state hook’s update function.
6405+
The effect hook called `useEffect` can be used to fetch data from an API and to set the data in the local state of the component with the useState hook’s update function.
64066406
6407-
Let's take an example in which it fetches list of react articles from the API
6407+
Here is an example of fetching a list of react articles from an API using fetch.
64086408
64096409
```javascript
6410-
import React, { useState, useEffect } from "react";
6411-
import axios from "axios";
6410+
import React from "react";
64126411

64136412
function App() {
6414-
const [data, setData] = useState({ hits: [] });
6413+
const [data, setData] = React.useState({ hits: [] });
64156414

6416-
useEffect(() => {
6417-
(async () => {
6418-
const result = await axios(
6419-
"http://hn.algolia.com/api/v1/search?query=react"
6420-
);
6421-
6422-
setData(result.data);
6423-
})();
6415+
React.useEffect(() => {
6416+
fetch("http://hn.algolia.com/api/v1/search?query=react")
6417+
.then(response => response.json())
6418+
.then(data => setData(data))
64246419
}, []);
64256420

64266421
return (
@@ -6437,7 +6432,9 @@ Learn to code and get hired with <a href="https://zerotomastery.io/?utm_source=g
64376432
export default App;
64386433
```
64396434
6440-
Remember we provided an empty array as second argument to the effect hook to avoid activating it on component updates but only on mounting of the component. i.e, It fetches only on component mount.
6435+
A popular way to simplify this is by using the library axios.
6436+
6437+
We provided an empty array as second argument to the useEffect hook to avoid activating it on component updates. This way, it only fetches on component mount.
64416438
64426439
**[⬆ Back to Top](#table-of-contents)**
64436440

0 commit comments

Comments
 (0)