Search code examples
reactjsmaterial-table

Is there a way to manually fire the isLoading animation from a custom action in material-table?


I'm using the material-table library. I'd like to use the current loading animation the library is using for a custom async operation. After clicking a custom action it turns on and then off when the aync has resolved.

import React from "react";
import MaterialTable from "material-table";
import ReactDOM from "react-dom";

import "./styles.css";

const handleAsync = () => {
  // isLoading = true
  // async done
  // isLoading = false
}

function App() {
  return (
    <MaterialTable
      columns={[
        {
          title: <button onClick={handleAsync}>async</button>
        },
        {
          title: "Avatar",
          field: "avatar",
          render: rowData => (
            <img
              style={{ height: 36, borderRadius: "50%" }}
              src={rowData.avatar}
            />
          )
        },
        { title: "Id", field: "id" },
        { title: "First Name", field: "first_name" },
        { title: "Last Name", field: "last_name" }
      ]}
      data={query =>
        new Promise((resolve, reject) => {
          let url = "https://reqres.in/api/users?";
          url += "per_page=" + query.pageSize;
          url += "&page=" + (query.page + 1);
          fetch(url)
            .then(response => response.json())
            .then(result => {
              resolve({
                data: result.data,
                page: result.page - 1,
                totalCount: result.total
              });
            });
        })
      }
      title="Remote Data Example"
    />
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Solution

  • You can use isLoading prop of material-table. Just like this:

    <MaterialTable
    ...//
    isLoading={this.state.isLoading}
    />
    

    Set your state.isLoading=true before your async operation and then set it false after operation completed