简体   繁体   English

在不刷新页面的情况下从 API 获取随机数据 axios

[英]Fetch random data from API without refreshing the page in react axios

How can I retrieve a specific data based on a key value passed to base API url. Here is the code for the component which retrieves the data using refreshing the page.如何根据传递给基数 API url 的键值检索特定数据。这是使用刷新页面检索数据的组件的代码。

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

import 'react-confirm-alert/src/react-confirm-alert.css'; // Import css
import { useDispatch, useSelector } from 'react-redux';
import { id, pid } from '../../../../auth/store/actions/index.js';
import http from '../../../../resources/http.js';

const AdminUpload = () => {
  const baseURL =
    'http://127.0.0.1:8000/api/business_process/get-my-business-process';
  const [file, setFile] = useState(null);
  const [client, setClient] = useState();
  const [showHide, setShowHide] = useState(false);
  const handleModalShowHide = () => setShowHide(!showHide);
  const [company_name, setCompany] = useState();
  const [data, setData] = useState([]);
  const [business_process, setBusinessProcess] = useState();
  let type = JSON.parse(localStorage.getItem('cyber-minds'));
  let clientID = type.user.client.id;
  const [datas, setDatas] = useState([]);
  const processId = useSelector((state) => state.pid);
  const dispatch = useDispatch();

  useEffect(() => {
    http
      .get(baseURL)
      .then((response) => {
        setData(response.data);
      })
      .then(
        (response) => {},
        (err) => {
          console.log(err);
        }
      );
    http
      .get(
        `http://127.0.0.1:8000/api/business_process/get-business-impact/${processId}`
      )
      .then((response) => {
        setDatas(response.data);
      })
      .then(
        (response) => {},
        (err) => {
          console.log('No Data To Show');
        }
      )
      .catch((err) => {
        return false;
      });
  }, []);
  console.log(data);
  const handleFile = (e) => {
    let file = e.target.files[0];
    setFile(file);
  };
  const handleUploadFile = (e) => {
    let myfile = file;

    let formData = new FormData();
    formData.append('file', myfile);
    formData.append('business_process', business_process);
    formData.append('businuss impact analysis', 'financial');
    http({
      url: 'http://127.0.0.1:8000/api/business_process/upload-business-impact-excel-by-clientadmin',
      method: 'POST',
      mode: 'cors',
      data: formData,
    }).then(
      (response) => {
        alert('File uploaded Sesscessfully');
      },
      (err) => {
        console.log(err);
      }
    );
  };
  const deleteBusinessImpact = (e) => {
    let myfile = file;

    let formData = new FormData();
    formData.append('file', myfile);
    formData.append('business_process', business_process);
    formData.append('businuss impact analysis', 'financial');
    http({
      url: `http://127.0.0.1:8000/api/business_process/get-business-impact/${processId}`,
      method: 'DELETE',
      mode: 'cors',
    }).then(
      (response) => {
        alert('File Deleted Successfully');
      },
      (err) => {
        console.log(err);
      }
    );
  };
  const refresh = () => {
    window.location.reload();
  };
  console.log('process id', processId);
  const DisplayData = datas?.map((asset) => {
    return (
      <tr>
        <td>{asset.hierarchy}</td>
        <td>{asset.business_assets}</td>
        <td>{asset.asset_name}</td>
        <td>{asset.vendors}</td>
        <td>{asset.product}</td>
        <td>{asset.version}</td>
        <td>{asset.cpe}</td>
        <td>{asset.asset_type}</td>
        <td>{asset.asset_categorization}</td>
        <td>{asset._regulations}</td>
        <td>{asset.asset_risk}</td>
      </tr>
    );
  });
  return (
    <>
      <div className=" flex flex-col space-y-6 justify-center mt-10 items-center">
        <h4>Uplaod Business Impact Analysis File</h4>
        <div class="search_categories w-96">
          <div class="select">
            <select
              value={business_process}
              onChange={(e) => {
                setBusinessProcess(e.target.value);
                dispatch(pid(e.target.value));
              }}
            >
              <option>Select Business Process</option>
              {data?.map((x, y) => (
                <option value={x.id}>{x.name}</option>
              ))}
            </select>
          </div>
        </div>
        {/* <h1>Upload Business Impact Analysis File</h1> */}
        <div className="flex space-x-4">
          <input type="file" name="file" onChange={(e) => handleFile(e)} />
        </div>
        <button
          className="color bg p-2 rounded-md w-72"
          type="button"
          onClick={(e) => refresh()} //show button with reloading the page
        >
          Show
        </button>
        <button
          className="color bg p-2 rounded-md w-72"
          type="button"
          onClick={(e) => handleUploadFile(e)}
        >
          Clear and Upload new file
        </button>
      </div>
      <div className="z-100">
        <div className="mt-36 flex space-x-10 justify-end items-end mr-16 text-lg">
          {/* <IconButton className="border-b">
            <EditIcon style={{ fontSize: 40 }} />
          </IconButton> */}

          <button
            className="color bg p-2 rounded-md"
            type="button"
            onClick={(e) => {
              deleteBusinessImpact(e);
              refresh();
              alert('Deleted Successfully');
            }}
          >
            Delete All Data
          </button>
        </div>
        <div className="text-black">
          <div className="rounded overflow-hidden flex  justify-center items-center">
            <table class="GeneratedTables">
              <thead>
                <tr>
                  <th className="detail text-2xl">Hierarchy</th>
                  <th className="color text-2xl">Business assets</th>
                  <th className="detail text-2xl">Asset Name</th>
                  <th className="color text-2xl">Vendors</th>
                  <th className="detail text-2xl">Product</th>
                  <th className="color text-2xl">Version</th>
                  <th className="detail text-2xl">CPE</th>
                  <th className="color text-2xl">Asset Type</th>
                  <th className="detail text-2xl">Asset Categorization</th>
                  <th className="color text-2xl">Regulations</th>
                  <th className="detail text-2xl">Asset Risk</th>
                </tr>
              </thead>
              <tbody>{DisplayData}</tbody>
            </table>
          </div>
        </div>
      </div>
    </>
  );
};

export default AdminUpload;

In the above code, when I click show button It reloads the page and retrieve the data based on the key value passed into the base URL. Without reloading the page, the data is not showing up.在上面的代码中,当我单击显示按钮时,它会重新加载页面并根据传递到基 URL 中的键值检索数据。如果不重新加载页面,则数据不会显示。 That's why I added reload functionality.这就是我添加重新加载功能的原因。

How can I implement show button to show data without actually reloading the page?如何在不实际重新加载页面的情况下实现显示按钮来显示数据?

Thanks谢谢

It seems that you are only updating the data in the backend, thus necessitating the "refresh" to refetch the data.看来您只是在后端更新数据,因此需要“刷新”来重新获取数据。 Instead of reloading the app you could just refetch the data.无需重新加载应用程序,您只需重新获取数据即可。

Refactor the two GET requests of in the useEffect hook into a standalone function to be called by the hook and at the end of the form submission.useEffect钩子中的两个 GET 请求重构为一个独立的 function 以供钩子调用,并在表单提交结束时调用。

Example:例子:

const fetchData = () => {
  http
    .get(baseURL)
    .then((response) => {
      setData(response.data);
    })
    .then(
      (response) => {},
      (err) => {
        console.log(err);
      }
    );
  http
    .get(
      `http://127.0.0.1:8000/api/business_process/get-business-impact/${processId}`
    )
    .then((response) => {
      setDatas(response.data);
    })
    .then(
      (response) => {},
      (err) => {
        console.log('No Data To Show');
      }
    )
    .catch((err) => {
      return false;
    });
};

useEffect(() => fetchData(), []);

...

<button
  className="color bg p-2 rounded-md w-72"
  type="button"
  onClick={fetchData}
>
  Show
</button>

...

<button
  className="color bg p-2 rounded-md"
  type="button"
  onClick={(e) => {
    deleteBusinessImpact(e);
    fetchData();
    alert('Deleted Successfully');
  }}
>
  Delete All Data
</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM