skip to Main Content

Fetching and displaying data in a table like view is working good.

I do have 3 labels with fields-> "user no, id number and lic no". I want to retrieve value input fields and call different fetch url accordingly. For ex: if user enters some particular user no, then i need to retrive that "user no" and call different fetch url in this method fetchTableData(). Could you please tell me, How do I retrieve value from the field and get that value into fetchTableData() function where i need to redirect URL based on the user input ?

import DataTable from "react-data-table-component"
import { useState, useEffect } from "react"

function App() {
    const [data, setData] = useState([])
    const [loading, setLoading] = useState(false)
    const [perPage, setPerPage] = useState(10)
    const [show, setShow] = useState(false);

    const columns = [
        {
            name: "Date",
            selector: (row) => row.memberno,
            width: "120px",
            wrap: true
        },
        {
            name: "Title",
            selector: (row) => row.title,
            wrap: true
        },
        {
            name: "ID Number",
            selector: (row) => row.dmnumber,
            wrap: true
        },
        {
            name: "License no",
            selector: (row) => row.documentid,
            wrap: true
        },
        {
            name: "Contact",
            selector: (row) => row.marketingcontact,
            wrap: true
        }
    ]

    useEffect(() => {
        fetchTableData()
    }, [])
    
    const handleSubmit = (e) => {
        e.preventDefault();
        setShow(true);
    };
    async function fetchTableData() {
        setLoading(true)
        const header = new Headers({ "Access-Control-Allow-Origin": "*" });

        // here i will be using different fetch url based on user inputs value for "user no or id number and lic no" 
        const response = await fetch('http://ec2-3-145-165-206.us-east-2.compute.amazonaws.com:8080/searchAll', { header: header })

        const users = await response.json()
        setData(users)
        setLoading(false)
    }

  return (
      <div className="wrapper">
        <h1> User Data Repo </h1>
        <form onSubmit={handleSubmit}>
          <fieldset>
            <label>
              <p>User Number:</p>
              <input name="userno" />
            </label>
              <label>
                  <p>ID Number:</p>
                  <input name="idnumber" />
              </label>
              <label>
                  <p>Lic Number:</p>
                  <input name="licnumber" />
              </label>
          </fieldset>

            <button type="submit" onClick={handleSubmit}>
                Submit
            </button>
        </form>

          <DataTable
              //title="Data"
              columns={columns}
              data={show ? data : []}
              progressPending={loading}
              pagination
          />
      </div>
  )
}

export default App;

2

Answers


  1. I don’t know well what you are saying. But in my opinion, you can do like the following code:

    import DataTable from "react-data-table-component";
    import { useState, useEffect } from "react";
    
    function App() {
      const [data, setData] = useState([]);
      const [loading, setLoading] = useState(false);
      const [perPage, setPerPage] = useState(10);
      const [show, setShow] = useState(false);
    
      const [userno, setUserno] = useState("");
      const [idnumber, setIdnumber] = useState("");
      const [licnumber, setLicnumber] = useState("");
    
      const columns = [
        {
          name: "Date",
          selector: (row) => row.memberno,
          width: "120px",
          wrap: true,
        },
        {
          name: "Title",
          selector: (row) => row.title,
          wrap: true,
        },
        {
          name: "ID Number",
          selector: (row) => row.dmnumber,
          wrap: true,
        },
        {
          name: "License no",
          selector: (row) => row.documentid,
          wrap: true,
        },
        {
          name: "Contact",
          selector: (row) => row.marketingcontact,
          wrap: true,
        },
      ];
    
      useEffect(() => {
        fetchTableData();
      }, []);
    
      const handleSubmit = (e) => {
        e.preventDefault();
        setShow(true);
        fetchTableData(userno, idnumber, licnumber); // pass the input values
      };
      async function fetchTableData() {
        setLoading(true);
        const header = new Headers({ "Access-Control-Allow-Origin": "*" });
    
        const server_url =
          "http://ec2-3-145-165-206.us-east-2.compute.amazonaws.com:8080";
        let url = `${server_url}/searchAll`; // default url
        if (userno) {
          // if user no is provided, use this url
          url = `${server_url}/searchByUserNo/${userno}`;
        } else if (idnumber) {
          // if id number is provided, use this url
          url = `${server_url}/searchByIdNumber/${idnumber}`;
        } else if (licnumber) {
          // if lic number is provided, use this url
          url = `${server_url}/searchByLicNumber/${licnumber}`;
        }
        const response = await fetch(url, { header: header });
        const users = await response.json();
        setData(users);
        setLoading(false);
      }
    
      return (
        <div className="wrapper">
          <h1> User Data Repo </h1>
          <form onSubmit={handleSubmit}>
            <fieldset>
              <label>
                <p>User Number:</p>
                <input
                  name="userno"
                  value={userno}
                  onChange={(e) => setUserno(e.target.value)}
                />
              </label>
              <label>
                <p>ID Number:</p>
                <input
                  name="idnumber"
                  value={idnumber}
                  onChange={(e) => setIdnumber(e.target.value)}
                />
              </label>
              <label>
                <p>Lic Number:</p>
                <input
                  name="licnumber"
                  value={licnumber}
                  onChange={(e) => setLicnumber(e.target.value)}
                />
              </label>
            </fieldset>
    
            <button type="submit" onClick={handleSubmit}>
              Submit
            </button>
          </form>
    
          <DataTable
            //title="Data"
            columns={columns}
            data={show ? data : []}
            progressPending={loading}
            pagination
          />
        </div>
      );
    }
    
    export default App;
    

    Of course, I may not understand you so my answer may be incorrect.

    Login or Signup to reply.
  2. First, you don’t want to use the same function, leave fetchTableData for the first render an create another function to achieve this behavior:

    async function fetParticularData() {
        //...
    }
    

    second in React we usually use onChange to update a state then give this latter as value to the input, so we can create only one state for all the inputs it is an object:

    const [form, setForm ] = useState({
     userno: "",
     idnumber: "",
     licnumber: ""
    })
    

    we bind it to our inputs:

    <fieldset>
      <label>
        <p>User Number:</p>
        <input
          name="userno"
          value={form.userno} 
          onChange={handleFormInputChange} />
      </label>
      <label>
        <p>ID Number:</p>
        <input
          name="idnumber"
          value={form.idnumber}
          onChange={handleFormInputChange}
        />
      </label>
      <label>
        <p>Lic Number:</p>
        <input
          name="licnumber"
          value={form.licnumber}
          onChange={handleFormInputChange}
        />
      </label>
    </fieldset>
    

    the handleFormInputChange function updates the form state based on e.target.name, it is the easiest way but we have to give the input name the same value of the coresponding property in the state object:

    function handleFormInputChange(e) {
      setForm((prev) => {
        return { ...prev, [e.target.name]: e.target.value };
      });
    }
    

    now when you want to fetch particular data you just call the fetParticularData function, you can have access to the inputs values from there:

    async function fetParticularData(){
      console.log("userno: ", form.userno);
      console.log("idnumber", form.idnumber);
      console.log("licnumber", form.licnumber);
      setLoading(true)
      // based on thesevalue you can create your logic then fetch data
      setData(users)
      setLoading(false)
    }
    

    or call it inside the submit function if you want:

    const handleSubmit = (e) => {
      e.preventDefault();
      setShow(true);
      fetParticularData()
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search