How to fetch data on Button click in React

Fetch data on Button click in React

This article will show you how to fetch data on Button click in React in two ways: using Axios or the fetch method. Let’s go into detail now.

Fetch data on Button click in React

When you do front-end programming, sometimes the request will be to fetch data when pressing a program button, like a side effect. Fetch API is a simple API for sending and receiving requests using js. With fetch, it’s easier to make web requests and handle responses than the old XMLHttpRequest.

Using Axios method

Axios is a Promise-based HTTP Client library for node.js and browsers. It is isomorphic (i.e., the same codebase can run in both the browser and node.js). On the server side, it uses the native HTTP module in node.js, and on the client side (browser), it uses XMLHttpRequest.

Terminal:

npm install Axios

After installing the Axios library, we can already use requests this way. For example, in the code below, we will use the get method to get the value from the todo list API.

Code:

import axios from 'axios';
import React from 'react';
import { useState } from 'react';
 
const App = () => {
  const [todo,setTodo] = useState({
    data: '',
    fetch: false
  })
 
  const handleClick = async() => {
    const data = await axios.get('https://jsonplaceholder.typicode.com/todos/1')
    setTodo({
        data: data,
        fetch: true
    })
  }
 
  return (
    <div className="container">
        <h2>Fetch data on Button click in React | LearnShareIT</h2>
        <hr/>
        <button onClick = {handleClick}>Get todo id = 1</button>
        <p>
            {todo.fetch===false?'':
           JSON.stringify(todo.data.data)}
        </p>
    </div>
  );
};
 
export default App;

Output:

So when we press the Button, the new program runs the function to fetch the API, returns the data to us, and prints it to the screen. Or you can refer to the following way to fetch data on Button click.

Using fetch method

We add the url for the retrieve as a parameter to fetch. In this case, the url is https://jsonplaceholder.typicode.com/todos/1. The fetch() method returns a promise with a resolves state, with the value being the response for that request.

When the promise resolves, the response is passed to. This is where the response can be used. If the request fails, it will go to .catch with the corresponding error parameter.

Code:

import React from 'react';
import { useState } from 'react';
 
const App = () => {
  const [todo,setTodo] = useState({
    data: '',
    fetch: false
  })
 
  const handleClick = async() => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then((response) => response.json())
  .then((data) => setTodo({
    data: data,
    fetch: true
    }));
  }
 
  return (
    <div className="container">
        <h2>Fetch data on Button click in React | LearnShareIT</h2>
        <hr/>
        <button onClick = {handleClick}>Get todo id = 1</button>
        <p>
            {todo.fetch===false?'':
           JSON.stringify(todo.data)}
        </p>
    </div>
  );
};
 
export default App;

The response returned by request contains the result and valuable properties and methods. Here we use response. fetch to evaluate the status of the response.

This way, the result returned to the program equals the Axios method, and you can fetch data on the Button click in React.

Summary

To sum up, you already know how to fetch data on Button click in React. I highly recommend you use the Axios method because it is more configurable. Good luck for you!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *