How to in React.js, make a axios.get call and display the response with a button click

Viewed 33

How to in React.js, make a axios.get call and display the response with a button click.

1 Answers

You can make one state then use useEffect hook to do that here is sample code:

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

const baseURL = "https://testing.com/posts/1";

export default function App() {
  var postFromResponse = null;
  const [post, setPost] = React.useState(null);

  React.useEffect(() => {
    axios.get(baseURL).then((response) => {
      postFromResponse = response.data;
    });
  }, []);

  function handleSubmit(e) {
   e.preventDefault();
   postFromResponse ? setPost(postFromResponse) : return null;
  }

  return (
    <div>
      {this.state.post &&
      <>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
      </>
      }
      <button onClick={handleSubmit}>
       Show Post
      </button>
    </div>
  );
}
Related