2

I'm using React as a display tool for my data, coupled with the framework react-table to list my data.

I have a field to create a new object in my data base but I can't reload the table without leaving my view.

My question, how to reuse the function to load the data? (source code)

class ElementCRDN extends React.Component {
    constructor(props) {
        super(props);
        this.handleCreation = this.handleCreation.bind(this);
        this.handleInput = this.handleInput.bind(this);
        this.state = {
            data: [], // the data retrieved from the server
            pages: -1,
       };
   }

   handleCreation(event) {
        Axios.post('/createElement', {
            // data
        }).then(() => {
            // Ask for reload
       });
       event.preventDefault();
   }

   render() {
       <form onSubmit={this.handleCreation}>
           // input to create object
       </form>
       <ReactTable
          data={this.state.data}
          pages={this.state.pages}
          loading={this.state.loading}
          manual
          columns={columns}
          onFetchData={(state) => { // function to retrieve the data
              this.setState({ loading: true });
              Axios.post('/listElements', {
                  page: state.page,
                  pageSize: state.pageSize,
                  sorted: state.sorted,
                  filtered: state.filtered,
              }).then((res) => {
                  this.setState({
                  data: res.data,
                  loading: false,
                  });
              });
          }}
       />
   }

Thank you for reading

4

1 回答 1

2

I would simply add the element to your data upon successful creation. You can use this.setState again with the new data value you were posting with createElement.

async handleCreation(event) {
  this.setState({ loading: true });
  await Axios.post('/createElement', data);
  this.setState({ data: this.state.data.concat(data), loading: false });
}
于 2018-05-07T16:21:16.310 回答