0

I'm still new to React and I'm using this library called axios to do API calls.

I had success on fetching login data for my web app. However, I'm having a hard time applying it onto a datatable.

Here is the code:

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;

See those hardcoded data? I want to make it dynamic by using API call.

Please guide me if what I am doing is correct.

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()

And then I would call retrieveClientDetails() in my page.

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

        }).catch(() => {

        })
      });

But, what parameters should I throw? Assuming I want to get all data.

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>>>")
        })
      });

2
  • 1
    set data as state const [data, setData] = useState([]) and in then set response as data setData(response.data) Commented Mar 20, 2020 at 7:04
  • It works! Another question though, how do I call setData upon load of page using React hooks? Thanks. Commented Mar 20, 2020 at 8:19

1 Answer 1

1

You need useEffect to setData upon load of page

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

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

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

useEffect(() => {
   fetchRequest();
}, []);
Sign up to request clarification or add additional context in comments.

5 Comments

For some reason, it didn't work and goes to the catch block. Is there a way for me to know what was the error? Thanks.
can you log your error, .catch((err) => {console.log(err) })
If you remove useEffect and fetch only by onClick, did it work?
ahh, i get it, it is error of Mockaroo api, please create another schemas and add new ApiUrl in axios and it will work
you can use this, i just create https://api.mockaroo.com/api/a693e710?count=1000&key=8cd4da00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.