Requesting an API endpoint

  • React
  • Examples
  • Requesting an API endpoint

React example • 2 min read

  • Async Requests

Here you can find some code samples on how to request an API endpoint that returns JSON, both with the native fetch method and also using the axios third-party npm module.

Using the native fetch method

You can play around with this code here.

import React from "react";

function App() {
  const handleClick = async () => {
    const res = await fetch("https://dog.ceo/api/breeds/image/random");
    const data = await res.json();
    console.log(data);
  };

  return (
    <div>
      <button onClick={handleClick}>Request API</button>
    </div>
  );
}

export default App;

Using axios 3rd-party module

You can play around with this code here.

import React from "react";
import axios from "axios";

function App() {
  const handleClick = async () => {
    const { data } = await axios({
      method: "GET",
      url: "https://dog.ceo/api/breeds/image/random"
    });
    console.log(data);
  };

  return (
    <div>
      <button onClick={handleClick}>Request API</button>
    </div>
  );
}

export default App;