react-bootstrap-table2 icon indicating copy to clipboard operation
react-bootstrap-table2 copied to clipboard

[Bug] Can't click radio button if using setState inside handleOnSelect

Open ngohungphuc opened this issue 8 years ago • 35 comments

Hi, I have this options

const selectRow = {
      mode: "radio",
      clickToSelect: true,
      onSelect: this.handleOnSelect
    };

 handleOnSelect = (row) => {
    //if using setState the radio button options will not show up, if remove setState everything ok
    this.setState({
      selectedId: row.userId
    });
  };

Below is error

2018-04-08_17-50-12

ngohungphuc avatar Apr 08 '18 10:04 ngohungphuc

@ngohungphuc did u use react-bootstrap-table2?

AllenFang avatar Apr 09 '18 15:04 AllenFang

@AllenFang yes of course. Here is my version

     "react-bootstrap-table-next": "^0.1.7",
    "react-bootstrap-table2-filter": "^0.1.5",
    "react-bootstrap-table2-overlay": "^0.1.1",
    "react-bootstrap-table2-paginator": "^0.1.1",

ngohungphuc avatar Apr 09 '18 15:04 ngohungphuc

@AllenFang @Chun-MingChen the error I get

Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component reactjs

ngohungphuc avatar Apr 10 '18 16:04 ngohungphuc

@AllenFang @Chun-MingChen any update about this is been 3 days

ngohungphuc avatar Apr 11 '18 09:04 ngohungphuc

i will switch to another plugin thank you

ngohungphuc avatar Apr 11 '18 12:04 ngohungphuc

sorry for lately reply, let me know if the problem still remain.

AllenFang avatar Apr 15 '18 03:04 AllenFang

the problem still remain

ngohungphuc avatar Apr 15 '18 03:04 ngohungphuc

@ngohungphuc any repo for reproducing this issue? we can't reproduce this by your example code, thanks

AllenFang avatar Apr 15 '18 13:04 AllenFang

@AllenFang Here is similar code. I try with previous version react-bootstrap-table and work fine

import BootstrapTable from "react-bootstrap-table-next";
class AccountTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedUserId: ""
    };
  }

  onSelectAccount = row => {
    //error occur in this setState
    this.setState({ selectedUserId: row.userId });
  };

  render() {
    const columns = [
      {
        dataField: "id",
        text: "Product ID"
      },
      {
        dataField: "name",
        text: "Product Name"
      },
      {
        dataField: "price",
        text: "Product Price"
      }
    ];

    const selectRow = {
      mode: "radio",
      clickToSelect: true,
      onSelect: this.onSelectAccount
    };

    return (
      <BootstrapTable
        keyField="id"
        data={products}
        columns={columns}
        selectRow={selectRow}
      />
    );
  }
}

export default AccountTable;

ngohungphuc avatar Apr 15 '18 14:04 ngohungphuc

@ngohungphuc I my opinion, setState will trigger the component render again, so in your case, it will make the react-bootstrap-table broken for selection row. If you really need to call setState, I will recommand you to also manage the selection by yourself:

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedUserId: ''
    };
  }

  onSelectAccount = (row) => {
    console.log(row);
    console.log(row.id);
    this.setState({ selectedUserId: row.id });
  };

  render() {
    const selectRow = {
      mode: 'radio',
      clickToSelect: true,
      selected: [this.state.selectedUserId],
      onSelect: this.onSelectAccount
    };

    return (
      <BootstrapTable
        keyField="id"
        data={ products }
        columns={ columns }
        selectRow={ selectRow }
      />
    );
  }
}

How do you think?

AllenFang avatar Apr 16 '18 15:04 AllenFang

@AllenFang your suggest not working

import React, { Component } from "react";
import { render } from "react-dom";
import BootstrapTable from "react-bootstrap-table-next";
import filterFactory, {
  textFilter,
  selectFilter
} from "react-bootstrap-table2-filter";
import paginationFactory from "react-bootstrap-table2-paginator";
import toastr from "toastr";
import qs from "qs";

import { validateInput } from "../../Helper/Validation";
import { isDomExist } from "../../Helper/util";
import { Get, Post } from "../../Helper/ajax";
import env from "../../Helper/envConfig";
import { APP_ENUM } from "./../../Helper/appEnum";

import ACCModal from "../../Common/ACCModal.jsx";

class AccountTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userList: [],
      loading: false,
      showModal: false,
      selectedUserId: "",
      btnActivate: "",
      btnDeactivate: "",
      toogleFlag: false,
      email: "",
      username: ""
    };

    this.validationObject = {};

    this.selectRow = {
      mode: "radio",
      clickToSelect: true,
      selected: [this.state.selectedUserId],
      onSelect: this.onSelectAccount
    };

    this.accountStatus = {
      True: "True",
      False: "False"
    };

    this.paginationOptions = {
      page: 1,
      sizePerPage: 5,
      pageStartIndex: 1,
      hideSizePerPage: true,
      prePage: "Prev",
      nextPage: "Next",
      firstPage: "First",
      lastPage: "Last"
    };

    this.addUserModalOptions = [
      {
        name: "username",
        type: APP_ENUM.INPUT_TEXT,
        required: "required"
      },
      {
        name: "email",
        type: APP_ENUM.INPUT_TEXT,
        required: "required"
      } /* ,
      {
        name: "Roles",
        type: APP_ENUM.SELECT,
        value: ["Admin", "Owner", "Editor"]
      } */
    ];

    this.columns = [
      {
        dataField: "userName",
        text: "User Name",
        filter: textFilter()
      },
      {
        dataField: "email",
        text: "Email",
        filter: textFilter()
      },
      {
        dataField: "emailConfirmed",
        text: "Email Confirmed",
        filter: selectFilter({
          options: this.accountStatus
        })
      },
      {
        dataField: "roles",
        text: "Roles"
      }
    ];
  }

  componentDidMount() {
    Get(env.userList).then(res => {
      this.setState({ userList: res.data });
    });
  }

  handleAddUser = () => {};

  toggleAccountStatus = () => {
    if (this.state.selectedUserId) {
      Post(
        env.deactiveAccount,
        qs.stringify({
          accountId: this.state.selectedUserId,
          toogleFlag: this.state.toogleFlag
        })
      )
        .then(() => {
          toastr.info("Account status successfully set");
        })
        .catch(() => {
          toastr.error("Something went wrong");
        });
    }
  };

  onSelectAccount = row => {
    if (row.emailConfirmed === "True") {
      this.setState({ btnDeactivate: "", btnActivate: "disabled" });
      this.setState({ selectedUserId: row.userId, toogleFlag: false });
    }
    if (row.emailConfirmed === "False") {
      this.setState({ btnActivate: "", btnDeactivate: "disabled" });
      this.setState({ selectedUserId: row.userId, toogleFlag: true });
    }
  };

  render() {
    const { userList, btnActivate, btnDeactivate } = this.state;

    this.validationObject = {
      username: this.state.username,
      email: this.state.email
    };

    const errors = validateInput.call(this, this.validationObject);

    return (
      <div className="card">
        <div className="card-header">User List</div>
        <div className="card-body">
          <div className="row" id="userListOptions">
            <div className="col-md-6">
              <button
                type="button"
                className="btn btn-primary"
                id="btnAddUser"
                data-toggle="modal"
                data-target="#addUserModal"
              >
                <i className="fa fa-user-plus" aria-hidden="true" />
                &nbsp; Add User
              </button>
              <ACCModal
                title="Add User"
                id="addUserModal"
                errors={errors}
                onClick={this.handleAddUser}
                options={this.addUserModalOptions}
              />
              <button type="button" className="btn btn-warning">
                <i className="fa fa-pencil-square-o" aria-hidden="true" /> Edit
                Role
              </button>
            </div>
            <div className="col-md-6" id="deactiveSection">
              <button
                type="button"
                className="btn btn-danger pull-right"
                onClick={this.toggleAccountStatus}
                disabled={btnDeactivate}
              >
                <i className="fa fa-power-off" aria-hidden="true" /> Deactive
                Account
              </button>
              <button
                type="button"
                className="btn btn-success pull-right"
                onClick={this.toggleAccountStatus}
                disabled={btnActivate}
              >
                <i className="fa fa-toggle-on" aria-hidden="true" />
                &nbsp; Activate Account
              </button>
            </div>
          </div>
          <BootstrapTable
            noDataIndication="Table is Empty"
            classes="table text-center table-hover table-bordered table-striped"
            keyField="userId"
            data={userList}
            columns={this.columns}
            filter={filterFactory()}
            pagination={paginationFactory(this.paginationOptions)}
            selectRow={this.selectRow}
          />
        </div>
      </div>
    );
  }
}

if (isDomExist("accountTable")) {
  render(<AccountTable />, document.getElementById("accountTable"));
}

ngohungphuc avatar Apr 17 '18 10:04 ngohungphuc

@ngohungphuc it work, please see me code again more carefully.

AllenFang avatar Apr 17 '18 14:04 AllenFang

I check my code with your code, they are same

ngohungphuc avatar Apr 17 '18 15:04 ngohungphuc

@AllenFang I am also having the same problem but I am using remote and redux. My redux state does not change but when an onClick event happens but it causes the table to re-render for some reason. This causes the selected row radio to not show and also makes my current page on the pagination shows 1 even though I am on page 4 for example.

xSynack avatar Apr 18 '18 17:04 xSynack

Here is what happens:

ezgif com-video-to-gif

xSynack avatar Apr 18 '18 17:04 xSynack

If someone would create a sandbox or something for this repo so @AllenFang can see, probably would help.

waynebrantley avatar May 02 '18 03:05 waynebrantley

@AllenFang Same problem occurs with multiple selection. Here is the codesandbox https://codesandbox.io/s/93jj53kkpp

remove the setState from the App part and try:

    this.setState({ 
      selection: selection
    });

redrobotdev avatar May 07 '18 22:05 redrobotdev

@ababakanian please check this example firstly.

AllenFang avatar May 12 '18 05:05 AllenFang

@ngohungphuc , you have mentioned that "it worked with previous version". Can you specify which version you are referring.

sanjesh avatar May 15 '18 15:05 sanjesh

@AllenFang in this example onSelect, onSelectAll methods explicitly set selected array in state

Is this the intended way of using onSelect, onSelectAll with state(or redux state) or is this a bug which will be fixed.

sanjesh avatar May 15 '18 15:05 sanjesh