The last thing I want to introduce in this tutorial is how to save the data we have in the table to localStorage, so that when we reload the page, the data is still there. We can close the browser, reopen it next week, and the data will still be there.

How do we do that?

We need to hook into the handleChangedCell() method of Table, and change it from:

handleChangedCell = ({ x, y }, value) => {
  const modifiedData = Object.assign({}, this.state.data)
  if (!modifiedData[y]) modifiedData[y] = {}
  modifiedData[y][x] = value
  this.setState({ data: modifiedData })
}

to:

handleChangedCell = ({ x, y }, value) => {
  const modifiedData = Object.assign({}, this.state.data)
  if (!modifiedData[y]) modifiedData[y] = {}
  modifiedData[y][x] = value
  this.setState({ data: modifiedData })

  if (window && window.localStorage) {
    window.localStorage.setItem(this.tableIdentifier,
      JSON.stringify(modifiedData))
  }
}

so that whenever a cell is changed, we store the state into localStorage.

We set tableIdentifier in the constructor, using

this.tableIdentifier = `tableData-${props.id}`

We use an id prop so that we can use multiple Table components in the same app, and they will all save on their own storage, by rendering them this way:

<Table x={4} y={4} id={'1'} />
<Table x={4} y={4} id={'2'} />

We now just need to load this state when the Table component is initialized, by adding a componentWillMount() method to Table:

componentWillMount() {
  if (this.props.saveToLocalStorage &&
      window &&
      window.localStorage) {
    const data = window.localStorage.getItem(this.tableIdentifier)
    if (data) {
      this.setState({ data: JSON.parse(data) })
    }
  }
}

Go to the next lesson