Home > database >  Axios call made before modal box opens
Axios call made before modal box opens

Time:09-24

I'm using bootstrap to open a modal. Previously I was trying to use a boolean to show/ close the modal but couldn't get it to work. Here is athe StackOverflow post where I was trying to get some help:

(How to open Bootstrap Modal from a button click in React)

The code below is making an AJAX request before a user has clicked the button to open the modal to present the user with some data.

This button is in a main page:

<td><button type="button" data-bs-toggle="modal" data-bs-target="#staticBackdrop" onClick={() => rowEvents(id)}>Compare</button></td>

I include this component in the main page which in effect is then making the axios request:

<ComparisonModal previousWon={previousWon} currentWon={currentWon} />


useEffect(() => {
    async function fetchData() {
        const content = await client.get('1');
    }
    fetchData();
}, []);

I'm quite new to React, is there a better way to do this so that the Axios call is not made until a user clicks on the button to show the modal please?

CodePudding user response:

I would try set a id to the button as it is a button on a table.

<td><button id="1" type="button" data-bs-toggle="modal" data-bs-target="#staticBackdrop" onClick={() => fetchData(id)}>Compare</button></td>

const fetchData = async (id) => {
   try {
         const content = await client.get(id);
       } catch (err) { 
         console.log(err);
       }
}

CodePudding user response:

Well, you have multiple questions at the same time, I just made this code sandbox as an example: https://codesandbox.io/s/relaxed-benji-8k0fr

Answering your questions:

  • Yes, you can show modal with a boolean. Basically would be like {booleanCondition && <MyModal />} (It's included in the code sandbox
  • Yes, you can do the axios request before when clicking the button. In the example we define a function: handleClick and on handleClick we do 2 things, getData which is a mocked request which last 3 seconds and setShowModal to be able to see the modal.

The result would be:

export default function App() {
  const [showModal, setShowModal] = React.useState(false);
  const [data, setData] = React.useState({});

  const getData = async (id) => {
    await wait(3000);
    setData({ loaded: id });
  };

  const handleClick = (id) => {
    setData({});
    setShowModal(true);
    getData(1);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={() => handleClick(1)}>Show Modal with Id 1</button>
      <button onClick={() => handleClick(2)}>Show Modal with Id 2</button>
      {showModal && <Modal data={data} onClose={() => setShowModal(false)} />}
    </div>
  );
}
  • Related