Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Fetch from external API function on button click

I'm trying to start an API call from a component when a user clicks a button. One URL param depends on the word a user selected before clicking the button. The fetch function is in an external function. When I call the function on button click and console log the result, it shows undefined, probably because of the async nature of the function.

How can I solve this if I want to put the fetch response into the App component state?

import { fetchAPI } from '../fetchAPI';

export default class App extends Component {

constructor() {
    super();
    this.toggleButtonState = this.toggleButtonState.bind(this);
    state = { ... }
}

toggleButtonState() {
    let selectedWord = window.getSelection().toString();
    fetchAPI(selectedWord);
    // call the fetchAPI function and put the result into state
}

export function fetchAPI(param) {
    // param is a highlighted word from the user before it clicked the button
    fetch('https://api.com/?param=' + param)
    .then(function(result) {
        return result;
    });
 }
like image 331
Doge Avatar asked Oct 30 '18 22:10

Doge


People also ask

How fetch data from API on button click in react JS?

To fetch data on button click in React: Set the onClick prop on a button element. Every time the button is clicked, make an HTTP request. Update the state variables and render the data.

How do you call a function on button click in react JS?

Example: Call a Function After Clicking a Buttonimport React from 'react'; function App() { function sayHello() { alert('Hello!' ); } return ( <button onClick={sayHello}> Click me!

How do you call API onClick in React?

The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.


1 Answers

You have to return the fetch request from your fetchAPI function, and you also want to add an additional then and give it a function in which you put the result in the state in the toggleButtonState function.

In your example the then inside the fetchAPI function is redundant, since it just returns the value as is. You can remove that and still get the same result.

Example

function fetch() {
  return new Promise(resolve => setTimeout(() => resolve(42), 1000));
}

function fetchAPI(param) {
  // param is a highlighted word from the user before it clicked the button
  return fetch("https://api.com/?param=" + param);
}

class App extends React.Component {
  state = { result: null };

  toggleButtonState = () => {
    let selectedWord = window.getSelection().toString();
    fetchAPI(selectedWord).then(result => {
      this.setState({ result });
    });
  };

  render() {
    return (
      <div>
        <button onClick={this.toggleButtonState}> Click me </button>
        <div>{this.state.result}</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
like image 191
Tholle Avatar answered Oct 05 '22 23:10

Tholle