Search code examples
reactjsaxiosserver-sidereact-table

React-Table not loading API data with server-side options enabled


I am using react-table version 6.9.2 to connect to an API and display the data. My initial implementation worked fine:

componentDidMount() {
    axios
        .get('http://jsonplaceholder.typicode.com/posts', {
            responseType: 'json'
        })
        .then((response) => {
            this.setState({ posts: response.data });
        });
}
return (
        <ReactTable
            columns={columns}
            data={this.state.posts}
            filterable
            defaultPageSize={5}
            noDataText={'Loading...'}
        />
    );

However I want to scale up my application and connect to a database and enable server side pagination. I followed the example provided: https://github.com/tannerlinsley/react-table/tree/v6#server-side-data

However the data is not being displayed when I implemented the below changes to my ReactTable

<ReactTable
        columns={columns}
        data={this.state.posts}
        pages={this.state.pages}
        loading={this.state.loading}
        filterable
        defaultPageSize={5}
        noDataText={"Loading..."}
        manual // informs React Table that you'll be handling sorting and pagination server-side
        onFetchData={(state, instance) => {
          // show the loading overlay
          this.setState({ loading: true });
          // fetch your data
          axios
            .post("http://jsonplaceholder.typicode.com/posts", {
              page: state.page,
              pageSize: state.pageSize,
              sorted: state.sorted,
              filtered: state.filtered
            })
            .then(res => {
              // Update react-table
              this.setState({
                posts: res.data,
                data: res.data.posts,
                pages: res.data.pages,
                loading: false
              });
            });
        }}
      />

I believe I am messing up with the onFetchData function but I am not entirely sure as to what. Is there a better way to enable this? Any help would be appreciated!

I've got a working code sandbox here: https://codesandbox.io/s/yp88v0kx2z


Solution

  • please make few corrections in urls,callback and axios

    https://codesandbox.io/s/lrn7j5vjrl?fontsize=14