Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Grids generated using array constructor autofill on first change event #16

Closed
CAYdenberg opened this issue Apr 30, 2017 · 2 comments
Closed

Comments

@CAYdenberg
Copy link

I'm not totally sure if this is a bug or just something improper with the way I'm going about this. I'm trying to auto-generate a 10-by-10 grid on init:

class Base extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      grid: Array(10).fill(Array(10).fill({})),
    }

    this._handleChange = this._handleChange.bind(this)
  }

  _handleChange(cell, colI, rowJ, value) {
    this.setState({
      grid: this.state.grid.map((col) =>
        col.map((rowCell) =>
          (rowCell === cell) ? ({value: value}) : rowCell
        )
      )
    })
  }

  render() {
    return (
      <DataSheet
        data={this.state.grid}
        valueRenderer={(cell) => cell.value}
        onChange={this._handleChange} />
    )
  }
}

export default Base

but when I do this, if I type anything into a cell, the entire grid gets filled with that value. After that it behaves as expected.

I can get any truthy or falsy value for that initial cell:

grid: Array(10).fill(Array(10).fill({value: null}))
grid: Array(10).fill(Array(10).fill({value: 0}))
grid: Array(10).fill(Array(10).fill({value: 1}))

all do the same thing.

@nadbm
Copy link
Owner

nadbm commented May 1, 2017

hey @CAYdenberg, your initialization is duplicating objects

var grid = Array(10).fill(Array(10).fill({value: null}));
console.log( grid[0] === grid[1] ) ) //true 
console.log( grid[0][0] === grid[1][0] ) ) //true

The way you're initializing essentially copies the same object. The handleChange method uses an object equality. Either change the method to use proper index or initialize your grid differently:

var grid = new Array(10).fill(null).map(v => Array(10));
grid = grid.map(row => row.fill(null).map(col => ({value: null}))); 
console.log( grid[0] === grid[1] ) ) //false 
console.log( grid[0][0] === grid[1][0] ) ) //false

@nadbm nadbm closed this as completed May 1, 2017
@CAYdenberg
Copy link
Author

Thanks for your response. That makes sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants