I still learn much React JavaScript and now I can’t understand how to create this initial state.
In the constructor
here in the code I want to add to state
by running this line:
JavaScript
x
2
1
this.state = CsvViewer.parse(props.data);
2
And direct after I want to add more state
variables like this:
JavaScript
1
6
1
this.state = {
2
filters: {},
3
sortColumn: null,
4
sortDirection: null,
5
};
6
The problem now is that state
does not contain the first call to CsvViewer
. How can I add to state both the call to CsvViewer
and the other state variables?
Code:
JavaScript
1
65
65
1
class CsvViewer extends Component {
2
static parse(data) {
3
const rows = [];
4
const columns = [];
5
6
new CSV(data).forEach(array => {
7
if (columns.length < 1) {
8
array.forEach((cell, idx) => {
9
columns.push({
10
key: `key-${idx}`,
11
name: cell,
12
resizable: true,
13
sortable: true,
14
filterable: true,
15
});
16
});
17
} else {
18
const row = {};
19
array.forEach((cell, idx) => {
20
row[`key-${idx}`] = cell;
21
});
22
rows.push(row);
23
}
24
});
25
return { rows, columns };
26
}
27
28
constructor(props) {
29
super();
30
this.state = CsvViewer.parse(props.data);
31
this.state = {
32
filters: {},
33
sortColumn: null,
34
sortDirection: null,
35
};
36
}
37
38
39
UNSAFE_componentWillReceiveProps(nextProps) {
40
// TODO
41
this.setState(CsvViewer.parse(nextProps.data));
42
}
43
44
handleGridSort = (sortColumn, sortDirection) => {
45
// this.setState({ sortColumn, sortDirection });
46
};
47
48
render() {
49
const { rows, columns } = this.state;
50
const { height } = this.props;
51
return (
52
<ReactDataGrid
53
enableCellAutoFocus={false}
54
columns={columns}
55
rowsCount={rows ? rows.length: 0}
56
rowGetter={i => rows[i]}
57
minHeight={height || 650}
58
onGridSort={this.handleGridSort}
59
/>
60
);
61
}
62
}
63
64
export default CsvViewer;
65
Advertisement
Answer
There’s a few options for adding properties to an object. Here’s the one i would usually do, using spread syntax. It will create a shallow copy of the object returned by parse, and add in the extra properties you define:
JavaScript
1
7
1
this.state = {
2
CsvViewer.parse(props.data),
3
filters: {},
4
sortColumn: null,
5
sortDirection: null,
6
}
7
Object.assign can be used to do something similar:
JavaScript
1
6
1
this.state = Object.assign({}, CsvViewer.parse(props.data), {
2
filters: {},
3
sortColumn: null,
4
sortDirection: null,
5
});
6
Or you could just add the individual properties one at a time:
JavaScript
1
5
1
this.state = CsvViewer.parse(props.data);
2
this.state.filters = {};
3
this.state.sortColumn = null;
4
this.state.sortDirection = null;
5