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

1
  • I posted an issue on the git too, I was missing a key feature of React: it does not rerender child component if their state does not change. @Explosion Pills was right, I needed to understand why Commented May 9, 2018 at 10:20

1 Answer 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 });
}
Sign up to request clarification or add additional context in comments.

1 Comment

This would work in most cases, but for me, the backend alter the data which prevent me from simply insert the sent data in the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.