I saw a react component that has the state
showed below:
class MyComp extends BaseComponent {
constructor(props) {
super(props);
this.state = {
selectedColumns: [],
params: {
offset: 0,
sort_by: {}
}
}
...
}
}
Then this react component has a method getValue
below. Inside this method allParams
object is created by using spread syntax. I.e. it is spreading methods argument params
, and after that updates params
object in components state.
getValue(params){
const allParams = {
...this.state.params,
...params
}
this.setState((prevState) => {
return {
...prevState,
params: allParams
}
})
...
}
It is then called like below in a child component inside MyComp
:
goNext() {
const offset = 15 // IT IS NOT JSON, it is a value 15.
this.props.getValue({
offset
})
}
I see that setState
is ok but is allParams
creation correct? Must not the params
be an object (json) to be used with ...
? Am i missing something?
In other cases the spread syntax is used like this:
const ob1 = {foo: 123};
const ob2 = {bar: 234};
const merged = {...ob1, ...ob2};
console.log(merged) //Output: { foo: 123, bar: 234 }
But in my case it would be:
const ob1 = {foo: 123};
const ob2 = 15;
const merged = {...ob1, ...ob2};
console.log(merged) //Output: { foo: 123}, and ob2 is not assigned!