Search code examples
reactjspromisefetchsetstatereact-table

Implementing nested fetch API calls with setInterval for dashboard: fetch()+React+Typesctipt


I am trying to bring up a dashboard page with a react table. I want table to be refreshed every 2 seconds.Also I have two fetch api calls , where result of the first one is passed as a parameter to the second. Also second fetch call must set the chart data every two seconds.

Also if there are multiple tables that follows the same implementation of such fetch calls, how can I do it?

What is the better way to do it?

Help would be appreciated

 import * as React from 'react';
 import ReactTable from 'react-table';
 import 'react-table/react-table.css';

 interface IState {
    data: any[];
 }

 export default class Dashboard extends React.Component<{},IState> {

   constructor(props: any) {
     super(props);
     this.state = {
       data: [],
   }

   componentDidMount()
   { 
       const url="/api/query/fetch";    

        var result = fetch(url, {
            method: 'post',
            body : JSON.stringify({"id":"abc"),
            headers: {
                     'Content-Type': 'application/json'
                    },
           }).then(function(response) {
        return response.json();

       }).then(function(data) {

        return fetch('api/query/fetch' + data.id); // want this call to be under setInterval such that chart data refreshes every 2 seconds, s uch that table data refreshes every 2 seconds
      })
      .then(function(response) {
           return response.json();
      })
      .catch(function(error) {
          console.log('Request failed', error)
      })
    result.then(function(r) {
         this.setState({data:r});
    });
  }     

  render(){
     return(
        <ReactTable 
           data={this.state.data} 
           columns={columns} //column config object
         />
     )   
  }
}

Solution

  • import * as React from 'react';
    import ReactTable from 'react-table';
    import 'react-table/react-table.css';
    
    interface IState {
        data: any[];
        id: any;
    }
    
    export default class Dashboard extends React.Component<{}, IState> {
    
        constructor(props: any) {
            super(props);
            this.state = {
                data: [],
                id: null
            }
        }
    
        componentDidMount() {
            const url = "/api/query/fetch";
    
            fetch(
                url, 
                {
                    method: 'post',
                    body: JSON.stringify({ "id": "abc"}),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
            ).then(function (response) {
                return response.json();
            }).then(function (data) {
                this.setState({
                    id: data.id
                }, () => this.fetchData())
            });
        }
    
        fetchData() {
            fetch('api/query/fetch' + this.state.id)
            .then(function (response) {
                return response.json();
            })
            .then(function (r) {
                this.setState({ data: r });
                setTimeout(() => {
                    this.fetchData();
                }, 2000);
            })
            .catch(function (error) {
                console.log('Request failed', error)
            })
        }
    
        render(){
            return (
                <ReactTable
                    data={this.state.data}
                    columns={columns} //column config object
                />
            )
        }
    }