Реакция. js + ax ios: Как избежать жесткого кодирования данных в моей базе данных? - PullRequest
0 голосов
/ 20 марта 2020

Я все еще новичок в React, и я использую эту библиотеку с именем ax ios для выполнения вызовов API.

Мне удалось получить данные для входа в мое веб-приложение. Однако мне трудно применить его к таблице данных.

Вот код:

ClientMaintancePage. js


    import React, {useState, useCallback} from 'react';
    import { MDBCard, MDBCardBody, MDBBreadcrumb, MDBBreadcrumbItem, MDBDataTable, MDBCol, MDBBtn } from 'mdbreact';
    import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
    import BootstrapTable from 'react-bootstrap-table-next';
    import paginationFactory from 'react-bootstrap-table2-paginator';
    import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
    import ClientMaintenanceService from '../../services/ClientMaintenanceService';
    import { ClientSaveSuccessModal } from '../modals/ClientSaveSuccessModal';
    import { ClientSaveFailedModal } from '../modals/ClientSaveFailedModal';

    const ClientMaintenancePage = () => {

      const [clientName, setClientName] = useState('');
      const [accountNumber, setAccountNumber] = useState('');

      const [disabled, setDisabled] = useState(true);

      const [showSuccessModal, setShowSuccessModal] = useState(false);
      const [showFailedModal, setShowFailedModal] = useState(false);

        const data = [
        {
          "id": 1,
          "clientname": "Hermann MacConchie",
          "accountnumber": "4905607119049823"
        }, {
          "id": 2,
          "clientname": "Aleksandr Tavernor",
          "accountnumber": "5641821398207954"
        }, {
          "id": 3,
          "clientname": "Starlin Yarrell",
          "accountnumber": "4175002190266301"
        }, {
          "id": 4,
          "clientname": "Windy Skully",
          "accountnumber": "30346494594931"
        }, {
          "id": 5,
          "clientname": "Den Scanlon",
          "accountnumber": "5100138355726726"
        }, {
          "id": 6,
          "clientname": "Bob Goldring",
          "accountnumber": "4844049813381927"
        }, {
          "id": 7,
          "clientname": "Isabella Gayne",
          "accountnumber": "6763633366420141"
        }, {
          "id": 8,
          "clientname": "Kerrill Capron",
          "accountnumber": "3564928342735986"
        }, {
          "id": 9,
          "clientname": "Butch Wharf",
          "accountnumber": "3565719211349309"
        }, {
          "id": 10,
          "clientname": "Mar Rase",
          "accountnumber": "3538926468850152"
        }, {
          "id": 11,
          "clientname": "Joyce Souness",
          "accountnumber": "201425016950947"
        }, {
          "id": 12,
          "clientname": "Loutitia Kettow",
          "accountnumber": "3541351118401527"
        }, {
          "id": 13,
          "clientname": "Debera Harroway",
          "accountnumber": "491154982724626720"
        }, {
          "id": 14,
          "clientname": "Alika Kerslake",
          "accountnumber": "30121249428796"
        }, {
          "id": 15,
          "clientname": "Stephine Lelievre",
          "accountnumber": "3568984382091125"
        }, {
          "id": 16,
          "clientname": "Jarrod Keneleyside",
          "accountnumber": "493673306153146174"
        }, {
          "id": 17,
          "clientname": "Saidee Peerman",
          "accountnumber": "372827642218552"
        }, {
          "id": 18,
          "clientname": "Cece Dimblebee",
          "accountnumber": "30444925316170"
        }, {
          "id": 19,
          "clientname": "Kurtis Twinbrow",
          "accountnumber": "06042486709242653"
        }, {
          "id": 20,
          "clientname": "Quillan Croyser",
          "accountnumber": "5602236291308592"
        }
      ];

      const columns = [
        {
        headerStyle: {
          backgroundColor: '#a6a6a6'
        },
        dataField: 'clientname',
        text: 'Client Name',
        sort: true,
        filter: textFilter()
        }, 

        {
        headerStyle: {
          backgroundColor: '#a6a6a6'
        },
        dataField: 'accountnumber',
        text: 'Account Number',
        sort: true,
        filter: textFilter()
        }
      ];

      const selectRow = {
        mode: 'radio',
        clickToSelect: true,
        hideSelectAll: true,
        onSelect: (row, isSelect, rowIndex) => {
          console.log(rowIndex);
          console.log(row.clientname);
          console.log(isSelect);
          setClientName(row.clientname);
          setAccountNumber(row.accountnumber);
        }
      };

      const fetchRequest = useCallback(() => {
        ClientMaintenanceService.saveClientDetails(clientName, accountNumber)
        .then((response) => {
          console.log("saveclientmaintenance response.data.result>>> " + response.data.result)
          if(response.data.result === "SUCCESS"){
            setShowSuccessModal(true);
            setShowFailedModal(false);
          }
        }).catch(() => {
          console.log("catch>>>")
            setShowSuccessModal(false);
            setShowFailedModal(true);
        })
      });

      const handleSuccessModalClose = () => {
        setShowSuccessModal(false)
        setClientName('')
        setAccountNumber('')
      }

      const handleFailedModalClose = () => {
        setShowFailedModal(false)
        setClientName('')
        setAccountNumber('')
      }

      const customTotal = (from, to, size) => (
        <span className="react-bootstrap-table-pagination-total">
          Showing { from } to { to } of { size } Results
        </span>
      );

      const options = {
        paginationSize: 4,
        pageStartIndex: 0,
        alwaysShowAllBtns: true, 
        hideSizePerPage: true,
        firstPageText: 'First',
        prePageText: 'Back',
        nextPageText: 'Next',
        lastPageText: 'Last',
        nextPageTitle: 'First page',
        prePageTitle: 'Pre page',
        firstPageTitle: 'Next page',
        lastPageTitle: 'Last page',
        showTotal: true,
        paginationTotalRenderer: customTotal,
        sizePerPageList: [{
          text: '5', value: 5
        }, {
          text: '10', value: 10
        }, {
          text: 'All', value: data.length
        }] 
      };

       return (
        <div>
        <MDBCard className="mb-2">
        <MDBCardBody id="breadcrumb" className="d-flex align-items-center justify-content-between">
          <MDBBreadcrumb>
            <MDBBreadcrumbItem>RPS</MDBBreadcrumbItem>
            <MDBBreadcrumbItem active>Client Maintenance</MDBBreadcrumbItem>
          </MDBBreadcrumb>
        </MDBCardBody>
        </MDBCard>

        <MDBCard className="mb-2">
          <MDBCardBody>
            <MDBCard className="mb-2">
              <MDBCardBody>
              <BootstrapTable
              keyField='id'
              hover
              data={ data }
              columns={ columns }
              filter={ filterFactory() }
              selectRow={ selectRow }
              noDataIndication="No record(s) found."
              pagination={ paginationFactory(options) }
              />
              </MDBCardBody>
              </MDBCard>
          </MDBCardBody>
          <MDBCol md="6">
            <form className="form-horizontal form-group">
            <label htmlFor="clientname" className="dark-grey-text">
                Client Name
            </label>
            <input type="text" id="clientname" className="form-control" 
                value={clientName} onChange={e => setClientName(e.target.value)} disabled={disabled} />
            <br />
            <label htmlFor="clientname" className="dark-grey-text">
                Account Number
            </label>
            <input type="text" id="accountnumber" className="form-control" maxLength="13" 
                value={accountNumber} onChange={e => setAccountNumber(e.target.value)} disabled={disabled} />
            <div className="text-right mt-2">
              <MDBBtn color="indigo" type="button" onClick={() => {setDisabled(false); setClientName(''); setAccountNumber('');}}>Add</MDBBtn>
              <MDBBtn color="indigo" type="button" onClick={() => {setDisabled(false);}}>Edit</MDBBtn>
              <MDBBtn color="indigo" type="button" onClick={() => {}}>Delete</MDBBtn>
              <MDBBtn color="indigo" type="button" onClick={() => {fetchRequest();}}>Save</MDBBtn>
            </div>
            </form>
          </MDBCol>
        </MDBCard>
        <ClientSaveSuccessModal 
            showSuccessModal={showSuccessModal} 
            handleSuccessModalClose={handleSuccessModalClose}
        />

        <ClientSaveFailedModal 
            showFailedModal={showFailedModal} 
            handleFailedModalClose={handleFailedModalClose}
        />
        </div>
      );
    }

    export default ClientMaintenancePage;

Видите эти жестко закодированные данные? Я хочу сделать его динамическим c с помощью вызова API.

Пожалуйста, сообщите мне, если то, что я делаю, правильно.

ClientMaintenanceService. js


    import axios from 'axios'

    const API_URL = 'http://localhost:8080'
    const API_URL2 = "https://api.mockaroo.com/api/2883cf10?count=1000&key=262bee40"

    class ClientMaintenanceService {

        saveClientDetails(clientname, accountnumber) {
            console.log("ClientMaintenanceService post request>>> " + clientname + " " + accountnumber)
            return axios.post(`${API_URL}/saveclientmaintenance`, {
                clientname,
                accountnumber
            })
        }

        retrieveClientDetails(){
            return axios.get(`${API_URL2}`)
        }
    }

    export default new ClientMaintenanceService()

И тогда я бы вызвал функцию retrieveClientDetails () на своей странице.

    const fetchRequest = useCallback(() => {
        ClientMaintenanceService.retrieveClientDetails()
        .then((response) => {

        }).catch(() => {

        })
      });

Но какие параметры мне следует выбросить? Предполагая, что я хочу получить все данные.

TIA

- EDIT -

ClientMaintenancePage. js


    const [data, setData] = useState([]);

      useEffect(() => {
        retrieveAllClient();
      }, []);

      const retrieveAllClient = useCallback(() => {
        ClientMaintenanceService.retrieveClientDetails()
        .then((response) => {
          console.log("retrieveAllClient response.data>>>" + response.data)
          setData(response.data)
        }).catch(() => {
          console.log("retrieveAllClient catch>>>")
        })
      });

1 Ответ

1 голос
/ 20 марта 2020

Вам нужно useEffect до setData при загрузке страницы

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

const [data, setData] = useState([]);

const fetchRequest = useCallback(() => {
    ClientMaintenanceService.retrieveClientDetails()
    .then((response) => {
         setData(response.data);
    }).catch(() => {})
});

useEffect(() => {
   fetchRequest();
}, []);
...