I use reactjs typescript on my project.
I use this lines of code :
if (reinitGridState) {
this.setState({
isbusy: false,
itemsList: data,
colList: columns,
gridState: this.initGridState,
gridData: process(data, this.initGridState)
});
} else {
this.setState({
isbusy: false,
colList: columns,
itemsList: data,
gridData: process(data, this.state.gridState)
});
}
And I want to remove the duplicate call of this.setState
I try this :
let newState = {
isbusy: false,
colList: columns,
itemsList: data,
gridData: process(data, this.state.gridState),
}
if (reinitGridState)
newState.gridState = this.initGridState;
this.setState(newState);
But an error occured : Property 'gridState' does not exist on type '{ isbusy: boolean; colList: DisplayGridColumn[]; itemsList: any; gridData: DataResult; }
How can I specify a type for variable newState
to add it dynamically the property gridState
and satisfy the type wanted for setState
?
PS : I don't want to use this newState["gridState"] = this.initGridState;
Thank you
CodePudding user response:
I believe you can resolve the error by defining the variable type, something like this (pseudocode).
interface MyState {
isbusy: boolean,
colList: ColumnType,
itemsList: DataType,
gridData: GridDataType,
gridState?: GridStateType
}
// ...
let newState: MyState = {
isbusy: false,
colList: columns,
itemsList: data,
gridData: process(data, this.state.gridState),
}
if (reinitGridState)
newState.gridState = this.initGridState;
this.setState(newState);
CodePudding user response:
I didn't find a suitable solution to my problem, but I use this which is cleaner than the old colde for me :
let newState = {
isbusy: false,
colList: columns,
itemsList: data,
gridData: process(data, this.state.gridState),
}
if (reinitGridState) {
this.setState({
...newState,
gridState: this.initGridState
});
} else {
this.setState(newState);
}