Fetch API Data on Button Click in React.
Published: 2022-07-03 11:55:06

### Prerequisites
JavaScript
React
### React Hooks

The React library has some hooks that help manage the state of various components without relying on classes.

The [useEffect](https://reactjs.org/docs/hooks-effect.html) hook is used for managing side effects such as fetching data in functional components.
Side effects are operations that change the state of a component outside a function.

- Let us see an example of how to use the useEffect hook to fetch data from the [JSON placeholder](https://jsonplaceholder.typicode.com/) API.

We can define a function to fetch data and call it within the useEffect hook.

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

function App() {
    const [data, setData] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch(`https://jsonplaceholder.typicode.com/albums/1`)
            const newData = await response.json()
            setData(newData)
        };

        fetchData();
    }, [])

    if (data) {
        console.log(data)
        return <div className='App'>{data.title}</div>;
    } else {
        return null;
    }
    
}

export default App;
```
`fetchData()` fetchs data from the API and sets the new state of the data.

```
You can use a library such as axios to make HTTP requests to APIs.
```
 
This retrieves details for the item with id 1 in the album api as shown below.

![useEffect](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xdu9yre3l7x3c8r6uxt.png)
useEffect runs after every render; it runs after the first render and every time there is an update.
We can use a dependency array to ensure the effect only runs when the state of id changes.

```javascript
useEffect(() => {
      const fetchData = async () => {
           const response = await fetch(`https://jsonplaceholder.typicode.com/albums/${id}`)
            const newData = await response.json()
            setData(newData)
        };

        fetchData();
    }, [id])   
}
```
We use the [useState](https://reactjs.org/docs/hooks-state.html) hook to store the state of the data retrieved from the API.

This function is useful when we need to retrieve data without relying on a specific event such as a mouse or button click.

Since useEffect runs the first time a component is mounted on the DOM we need to find a way to only fetch data when an event occurs especially when we are dependent on user input.

## Fetch Data on Button Click

We can use a custom function to fetch data without relying on useEffect to avoid calling the API each time there is an update.

A user submits an id for the item they would like to retrieve. This makes the id field dynamic.
- Getting User Input
```javascript
<input className='album_id' required="required" placeholder='Enter an ID'/>
<button type="submit">Search</button>
```
- Handling user input
```javascript
const [id, setId] = useState('')
const [data, setData] = useState(null)
    
const handleClick = async () => {
        try {
            const data = await (await fetch(`https://jsonplaceholder.typicode.com/albums/${id}`)).json()
            setData(data)
        } catch (err) {
            console.log(err.message)
        }
    }
 return (
        <div>
            <input className='album_id' required="required" placeholder='Enter an ID' value={id} onChange={e => setId(e.target.value)} />

            <button type="submit" onClick={handleClick} >Search</button>
           
        </div>
    )
```
We define an id variable and store its state using the setId function and supply the Id to the URL.

![User Input](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7nf2bpi386hlkp76o59.png)
We can also customize the output displayed depending on whether we get the expected response from the API.

```javascript
function checkResponse(data) {
        if (data) {
            console.log(data)
            return <div className='App'>{data.title}</div>;
        } else {
            return null;
        }
    }
```
`checkResponse()` is used to render different output depending on the state of the response.

[Here](https://github.com/wanguiwaweru/Fetching-API-Data-in-React) is the complete code used in this post.
Happy learning !!!