0

I have a table component that I am using to display the information from all other components in my app. This means that when I send data I can't use the following:

db.collection(collectionName).add({
  key1: val1,
  key2: val2,
  etc...
})

Because the keys could be different depending on which component is using table. I've thought about doing this with a .map() or forEach going through each key but I keep getting syntax errors.

I originally assumed that I could just send the object new_row but that doesn't seem to work properly.

Here is my table component:

class Table extends Component {
constructor(props){
    super(props);
    this.state = {
        rows: null,
        temprows: null,
        newrow: null,
        parent: this.props.tableComponent
    }
}
    addRow = function(){
      var new_rows = [...this.state.rows];
      new_rows.push(this.state.newrow);
      var new_row = JSON.parse(JSON.stringify(new_rows[0]));

      Object.keys(new_row).forEach(function(index) {
        new_row[index] = '';
      });

      db.collection(collectionNAame).add({
         I want to add the data here
      })

      this.setState({
        rows: new_rows,
        newrow: new_row
      });
}

Is there also a better approach, some other method aside from .add for this specific case?

2
  • what are you passing to .add? Commented May 8, 2020 at 3:52
  • That's what I'm trying to figure out. I originally thought I could just put new_row in .add() but that didn't work. Commented May 8, 2020 at 3:56

1 Answer 1

1

In db.collection .add method, spread and pass this.state.newrow and in the then block update your state. Also in your addRow function, the new_row should be obtained from state (not new_rows[0]

Like this

class Table extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rows: null,
      temprows: null,
      newrow: {},
      parent: this.props.tableComponent
    };
  }
  addRow = function() {
    var new_rows = [...this.state.rows];
    new_rows.push(this.state.newrow);
    //   var new_row = JSON.parse(JSON.stringify(new_rows[0]));
    var new_row = { ...this.state.newrow };

    db.collection(collectionNAame)
      .add({
        ...this.state.new_row
      })
      .then(() => {
        Object.keys(new_row).forEach(function(index) {
          new_row[index] = "";
        });
        this.setState({
          rows: new_rows,
          newrow: new_row
        });
      });
  };
}

Sign up to request clarification or add additional context in comments.

Comments

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.