Skip to content

Update answer to question 303 #224

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6404,25 +6404,20 @@ Learn to code and get hired with <a href="https://zerotomastery.io/?utm_source=g

303. ### How to fetch data with React Hooks?

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.
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.

Let's take an example in which it fetches list of react articles from the API
Here is an example of fetching a list of react articles from an API using fetch.

```javascript
import React, { useState, useEffect } from "react";
import axios from "axios";
import React from "react";

function App() {
const [data, setData] = useState({ hits: [] });
const [data, setData] = React.useState({ hits: [] });

useEffect(() => {
(async () => {
const result = await axios(
"http://hn.algolia.com/api/v1/search?query=react"
);

setData(result.data);
})();
React.useEffect(() => {
fetch("http://hn.algolia.com/api/v1/search?query=react")
.then(response => response.json())
.then(data => setData(data))
}, []);

return (
Expand All @@ -6439,7 +6434,9 @@ Learn to code and get hired with <a href="https://zerotomastery.io/?utm_source=g
export default App;
```

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.
A popular way to simplify this is by using the library axios.

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.

**[⬆ Back to Top](#table-of-contents)**

Expand Down