DEV Community

Bernice Waweru
Bernice Waweru

Posted on • Updated on

Fetch API Data on Button Click in React.

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 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 use see an example of how to use the useEffect hook to fetch data from the JSON placeholder API.

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

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;
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

This retrieves details for the item with id 1 in the album api as shown below.

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

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

        fetchData();
    }, [id])   
}
Enter fullscreen mode Exit fullscreen mode

We use the useState 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 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
<input className='album_id' required="required" placeholder='Enter an ID'/>
<button type="submit">Search</button>
Enter fullscreen mode Exit fullscreen mode
  • Handling user input
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>
    )
Enter fullscreen mode Exit fullscreen mode

We define an id variable and store its state using the setId function and supply the Id to the URL.

User Input
We can also customize the output displayed depending on whether we get the expected response from the API.

function checkResponse(data) {
        if (data) {
            console.log(data)
            return <div className='App'>{data.title}</div>;
        } else {
            return null;
        }
    }
Enter fullscreen mode Exit fullscreen mode

checkResponse() is used to render different output depending on the state of the response.

Here is the complete code used in this post.
Happy learning !!!

Discussion (0)