0

In react js how to fetch api data dynamically on the basis of click button.in my below code i want to fetch data on the basis of click using react js .how can we do that .

https://mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d my api is this.in my below code i make one table and i want when i click on row 1st that is airplane and when i click first row then fetch airplane data using this api https://mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d .

how can we do that.

is there any help.its very thankful.

var TableComponent = React.createClass({
  render: function() {
    // Data
    var dataColumns = this.props.data.columns;
    var dataRows = this.props.data.rows;

    var tableHeaders = (<thead>
          <tr>
            {dataColumns.map(function(column) {
              return <th>{column}</th>; })}
          </tr>
      </thead>);

 var tableBody = dataRows.map(function(row) {
      return (
        <tr>
          {dataColumns.map(function(column) {
            return <td>{row[column]}</td>; })}
        </tr>); });
    // Decorate with Bootstrap CSS
    return (<table className="table table-bordered table-hover" width="100%">
        {tableHeaders}
        {tableBody}
      </table>) }});
        

// Example Data
var tableData = {
 columns: ['Service_Name', 'Cost/Unit'],
  rows: [{
    'Service_Name': 'airplane',
    'Cost/Unit': 50
   
  }, {
    'Service_Name': 'cat',
    'Cost/Unit': 50
  },{
    'Service_Name': 'fruits',
    'Cost/Unit': 50
  }, {
    'Service_Name': 'pool',
    'Cost/Unit': 50
  }]
};

ReactDOM.render(
  <TableComponent data = {tableData} />,
  document.getElementById('table-component'));
9
  • codepen.io/kupraveen/pen/poRYJOM plz check my code here Commented Apr 26, 2021 at 10:33
  • anybody help me out?? how can we do fetch api dynamically Commented Apr 26, 2021 at 10:33
  • anyone help me out i m totally new in this Commented Apr 26, 2021 at 10:35
  • You want to fetch a document on clicking a table cell? Commented Apr 26, 2021 at 10:37
  • Add onClick event where you want, fetch your data and save it to React state. When the state is updated, UI will be re-rendered automatically. Commented Apr 26, 2021 at 10:39

2 Answers 2

1

I hope it will help:

const MyTable = ({data}) => {
  const fetchSomething = serviceName => fetch(`https://whatever?service_name=${serviceName}`).then(...);

  return (
    <Table>
      <tr>
        {data.columns.map(column => (<th key={column}>{column}</th>))}
      </tr>
      {data.rows.map((row, index) => (
        <tr key={index} onClick={fetchSomething(row['Service_Name'])}>
          <td>{row['Service_Name']}</td>
          <td>{row['Cost/Unit']}</td>
        </tr>
      ))}
    </Table>
    )
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for reply can u show me something in codepen or codesandbox because i m not able to do that codepen.io/kupraveen/pen/poRYJOM here is my code and api link is there mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d
its very thankful if u can help me i m stuck on that
Nice solution, Michael! Seems to be more elegant than mine :)
its should not work i m checking now can u help m to show
1

Probably you need something like this. Steps for implementation:

  1. Add a click listener on your row
  2. Implement handleRowClick function similar to the below implementation. Save all that you need from the response to the React state.
  3. Show the result somewhere in UI, or just console.log it.

Here is some code below that might help you

class TableComponent extends React.Component {
  state = {};

  handleRowClick = async () => {
    // make an API call here, sth like
    const url = "https://mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d";
    const response = await fetch(url);
    this.setState({
      ...response,
    });
  };

  render() {
    var dataColumns = this.props.data.columns;
    var dataRows = this.props.data.rows;

    var tableHeaders = (
      <thead>
        <tr>
          {" "}
          {dataColumns.map(function (column) {
            return <th> {column} </th>;
          })}{" "}
        </tr>{" "}
      </thead>
    );

    var tableBody = dataRows.map((row) => {
      return (
        <tr onClick={this.handleRowClick}>
          {" "}
          {dataColumns.map(function (column) {
            return (
              <td>
                {" "}
                <a target="_blank" rel="noopener noreferrer" href={row.url}>
                  {" "}
                  {row[column]}{" "}
                </a>
              </td>
            );
          })}{" "}
        </tr>
      );
    });

    // Decorate with Bootstrap CSS
    return (
      <table className="table table-bordered table-hover" width="100%">
        {" "}
        {tableHeaders} {tableBody}{" "}
      </table>
    );
  }
}

// Example Data
var tableData = {
  columns: ["Service_Name", "Cost/Unit", "Unit", "Units Requested"],
  rows: [
    {
      Service_Name: "airplane",
      "Cost/Unit": 50,
      Unit: "1 Hour",
      "Units Requested": 12,
      url:
        "http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png",
    },
    {
      Service_Name: "cat",
      "Cost/Unit": 50,
      Unit: "1 Hour",
      "Units Requested": 12,
      url:
        "http://codeskulptor-assets.commondatastorage.googleapis.com/assets_clock_background.png",
    },
    {
      Service_Name: "fruits",
      "Cost/Unit": 50,
      Unit: "1 Hour",
      "Units Requested": 12,
      url:
        "http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blend.png",
    },
    {
      Service_Name: "pool",
      "Cost/Unit": 50,
      Unit: "1 Hour",
      "Units Requested": 12,
    },
  ],
};

ReactDOM.render(
  <TableComponent data={tableData} />,
  document.getElementById("table-component")
);

5 Comments

can u show me something in code editorbcz its not work which u have share with me.its very helpful for me
@praveenakumari just take the Virtuoz component 'as is' and pass the table data as props, it should work.
codepen.io/kupraveen/pen/poRYJOM can u show me its very thankful. here codepen.io/kupraveen/pen/poRYJOM just now i check its not happen
You won't manage it to work from codepen, because there is no Access-Control-Allow-Origin header on the requested resource. Either run Chrome in disabled CORS mode or set the needed header on the server side.

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.