Skip to content

Instantly share code, notes, and snippets.

@vamsee9
Created December 5, 2022 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vamsee9/c375f421be700e7bf8a63eaf1a618c4f to your computer and use it in GitHub Desktop.
Save vamsee9/c375f421be700e7bf8a63eaf1a618c4f to your computer and use it in GitHub Desktop.

Here is an example of how you could use React and Ajax to create a component that fetches data from an API when a button is clicked, and then hides the button after it has been clicked:

import React, { useState } from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [buttonHidden, setButtonHidden] = useState(false);

  const fetchData = async () => {
    // Fetch data from API here
    const response = await axios.get('https://example.com/api/endpoint');
    setData(response.data);
    setButtonHidden(true);
  };

  return (
    <div>
      {buttonHidden ? null : <button onClick={fetchData}>Fetch Data</button>}
      {data ? <p>Data: {data}</p> : null}
    </div>
  );
};

n this example, the MyComponent component uses React's useState hook to manage its state. The data state variable is used to store the data that is fetched from the API, and the buttonHidden state variable is used to track whether the button should be displayed or not.

When the MyComponent component is rendered, it will display a button that says "Fetch Data". When the button is clicked, the fetchData function is called, which uses the axios library to fetch data from the specified API endpoint. Once the data is fetched, it is stored in the data state variable, and the buttonHidden state variable is set to true, which hides the button.

The component then renders the data that was fetched, or displays nothing if the data has not yet been fetched.

This is just one possible way to implement this functionality using React and Ajax. There are many other ways you could achieve the same result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment