0

I've written a ReactJS app, where I have list of data (JSON data) showed in table view. I've used "react-data-table-component" for that. It works fine, right now whenever the app launches it fetches and displays the data in table UI. But, I want to display this JSON data only when user clicks on "Submit" button <button type="submit">Submit</button>. I have pasted the code below. I am not able to use either <button onClick to display the data using DataTable or not able to achieve this. Could you please help me how can I display data only clicking on Submit button?

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 columns = [
        {
            name: "In Market Date",
            selector: (row) => row.userId,
            width: "120px",
            wrap: true
        },
        {
            name: "Topic/Title",
            selector: (row) => row.title,
            wrap: true
        },
        {
            name: "Sl Number",
            selector: (row) => row.title,
            wrap: true
        },
        {
            name: "Document ID",
            selector: (row) => row.title,
            wrap: true
        },
        {
            name: "Meeting Contact",
            selector: (row) => row.title,
            wrap: true
        },
        {
            name: "Reference",
            selector: (row) => (row.completed ? "Yes" : "No"),
            wrap: true
        },
    ]

    useEffect(() => {
        fetchTableData()
    }, [])

    async function fetchTableData() {
        setLoading(true)
        
        const response = await fetch('https://jsonplaceholder.typicode.com/todos')

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

  return (
      <div className="wrapper">
        <h1> User info </h1>
        <form>
          <fieldset>
            <label>
              <p>User Name:</p>
              <input name="name" />
            </label>
              <label>
                  <p>DM Number:</p>
                  <input name="number" />
              </label>
              <label>
                  <p>Document ID:</p>
                  <input name="docnumber" />
              </label>
          </fieldset>
          <button type="submit">Submit</button>

        </form>

          <DataTable
              //title="Data"
              columns={columns}
              data={data}
              progressPending={loading}
              pagination
          />


      </div>

  )
}

export default App;

2 Answers 2

1

There many ways to do that. One simple solution is to add another useState for keeping a show/hide bool flag, false by default. When the submit button is clicked, just to set the flag to true, and also pass table data based on the flag value. Here is an example I made: https://codesandbox.io/s/interesting-violet-rg7y6s?file=/src/App.js

A better way to do the whole thing could be using "react-query", which allows you not to fetch data by default, but fetch data manually when the submit button is clicked.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh wow. It looks simple. I have an additional question. What if I want to pass form data (for ex: user enters 'DM number' and then click Submit? how can the submit function receive this value and then request server synchronous or async way to get data and display in table? how to pass value to handlesubmit function, then handlesubmit function will call fetch("jsonplaceholder.typicode.com/todos") based on passing a parameter (for ex: jsonplaceholder.typicode.com/todos/dmnumber)?
@Stella I suggest you to use react-hook-form react-hook-form.com/get-started to do complex form related tasks.
1

You could create a variable to keep track of the submit button

const [submitClicked, setSubmitClicked] = useState(false);

Then create a function that handles the submit

async function handleSubmit(event) {
  event.preventDefault();
  setLoading(true);
  
  const formData = {
    name: event.target.name.value,
    number: event.target.number.value,
    docnumber: event.target.docnumber.value
  };
  
  const response = await fetch('https://jsonplaceholder.typicode.com/todos');
  const users = await response.json();
  setData(users);
  setLoading(false);
  setSubmitClicked(true);
}

An then render the table only if submit == true

{submitClicked && (
  <DataTable
    columns={columns}
    data={data}
    progressPending={loading}
    pagination
  />
)}

Also, you need to create the submit function

Here is the code with the changes

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

function App() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [submitClicked, setSubmitClicked] = useState(false);

  const columns = [
    {
      name: "In Market Date",
      selector: (row) => row.userId,
      width: "120px",
      wrap: true
    },
    {
      name: "Topic/Title",
      selector: (row) => row.title,
      wrap: true
    },
    {
      name: "Sl Number",
      selector: (row) => row.title,
      wrap: true
    },
    {
      name: "Document ID",
      selector: (row) => row.title,
      wrap: true
    },
    {
      name: "Meeting Contact",
      selector: (row) => row.title,
      wrap: true
    },
    {
      name: "Reference",
      selector: (row) => (row.completed ? "Yes" : "No"),
      wrap: true
    },
  ];

  async function handleSubmit(event) {
    event.preventDefault();
    setLoading(true);

    const formData = {
      name: event.target.name.value,
      number: event.target.number.value,
      docnumber: event.target.docnumber.value
    };

    const response = await fetch('https://jsonplaceholder.typicode.com/todos');
    const users = await response.json();
    setData(users);
    setLoading(false);
    setSubmitClicked(true);
  }

  return (
    <div className="wrapper">
      <h1> User info </h1>
      <form onSubmit={handleSubmit}>
        <fieldset>
          <label>
            <p>User Name:</p>
            <input name="name" />
          </label>
          <label>
            <p>DM Number:</p>
            <input name="number" />
          </label>
          <label>
            <p>Document ID:</p>
            <input name="docnumber" />
          </label>
        </fieldset>
        <button type="submit">Submit</button>
      </form>

      {submitClicked && (
        <DataTable
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
        />
      )}
    </div>
  );
}

export default App;

Please let me know if this worked for you

EDIT for "What if I want to pass form data (for ex: user enters 'DM number' and then click Submit? how can the submit function receive this value and then request server synchronous or async way to get data and display in table?" comment:

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

function App() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [submitClicked, setSubmitClicked] = useState(false);

  const columns = [
    {
      name: "In Market Date",
      selector: (row) => row.userId,
      width: "120px",
      wrap: true
    },
    {
      name: "Topic/Title",
      selector: (row) => row.title,
      wrap: true
    },
    {
      name: "Sl Number",
      selector: (row) => row.title,
      wrap: true
    },
    {
      name: "Document ID",
      selector: (row) => row.title,
      wrap: true
    },
    {
      name: "Meeting Contact",
      selector: (row) => row.title,
      wrap: true
    },
    {
      name: "Reference",
      selector: (row) => (row.completed ? "Yes" : "No"),
      wrap: true
    },
  ];

  async function handleSubmit(formData) {
    setLoading(true);

    const response = await fetch('https://jsonplaceholder.typicode.com/todos');
    const users = await response.json();
    setData(users);
    setLoading(false);
    setSubmitClicked(true);
  }

  return (
    <div className="wrapper">
      <h1> User info </h1>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          const formData = new FormData(event.target);
          const formDataObj = Object.fromEntries(formData.entries());
          handleSubmit(formDataObj);
        }}
      >
        <fieldset>
          <label>
            <p>User Name:</p>
            <input name="name" />
          </label>
          <label>
            <p>DM Number:</p>
            <input name="number" />
          </label>
          <label>
            <p>Document ID:</p>
            <input name="docnumber" />
          </label>
        </fieldset>
        <button type="submit">Submit</button>
      </form>

      {submitClicked && (
        <DataTable
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
        />
      )}
    </div>
  );
}

export default App;

You should change the endpoint "https://placeholderURL/todos" for the one that returns the data

1 Comment

Oh, thank you So much Alexander. I got it. I have an additional question. What if I want to pass form data (for ex: user enters 'DM number' and then click Submit? how can the submit function receive this value and then request server synchronous or async way to get data and display in table?

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.