1

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

3

1 Answer 1

2

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
   });
Sign up to request clarification or add additional context in comments.

Comments

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.