Sarvesh Agarwal
Sarvesh Agarwal

Reputation: 152

Use output from axios API in one function and pass to another

Team any better way to get data from Axios API and then use it in the same function as data.

import React, { Component, useState, useMemo } from 'react';
import { useTable } from 'react-table';
import { COLUMNS } from './columns';
import axios from 'axios';


export const BasicTable = () => {
      const [myresponse, setmyresponse] =useState([]);
      axios.get('http://localhost:5001/inventory/cluster/cluster1/servertype/test1')
      .then((response) => {
        const myresponse= response.data;
        setmyresponse(myresponse)
      });

      const columns = useMemo(() => COLUMNS, [])
      const data = useMemo(() => myresponse,[])
      const tableInstance = useTable({
        columns: columns,
        data: data
      })
      
    const { getTableProps,getTableBodyProps, headerGroups,rows,prepareRow } =tableInstance
    
    return(
      <table {...getTableProps()}>
          <thead >
            {headerGroups.map(headerGroup => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {
                headerGroup.headers.map(column =>(
                  <th {...column.getHeaderProps()}>{column.render('Header')}</th>
                ))}
            </tr>
            ))}
          </thead>

          <tbody {...getTableBodyProps()}>
            {
              rows.map(row => {
                prepareRow(row)
                return (
                  <tr {...row.getRowProps()}>
                    {
                      row.cells.map(cell =>{
                        return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                      })
                    }

                </tr>
                )
              })
            }

          </tbody>
      </table>
    )
};

What's happening right now, is I get data using console.log but the requests keep running indefinitely to my Axios API. Any thoughts on what am doing wrong? enter image description here

Upvotes: 1

Views: 680

Answers (1)

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

Just do this: I have used useEffect so that your API gets called only once after your component did mount.

  useEffect(() => {
     axios
       .get('http://localhost:5001/inventory/cluster/cluster1/servertype/test1')   
       .then((response) => {
            const myresponse= response.data;
            setmyresponse(myresponse)
        });
   }, [])
    
   const columns = useMemo(() => COLUMNS, [])
   const data = useMemo(() => myresponse,[myresponse])
   const tableInstance = useTable({
      columns: columns,
      data: data
   });

Upvotes: 2

Related Questions