Reputation: 6603
Is it the right way to call setState as a callback in another one? Here a piece of my code.
This is my initial state:
state = {
resumeCollection: [],
filters: {
educationLevels: [],
educationFields: [],
jobAdvertisementId: []
}
};
And this a componentDidMount section:
componentDidMount() {
this.setState(prevState =>( {filters : {
jobAdvertisementId : [...prevState.filters.jobAdvertisementId, {value: this.props.router.query.value, id: this.props.router.query.id}]}
}
)
, () => this.setState(state => {
return({
resumeCollection : state.resumeCollection.filter(resume => resume.jobAdvertisementId == state.filters.jobAdvertisementId[0].id )
});
}
)
)
}
Upvotes: 2
Views: 108
Reputation: 31014
I would advice against doing 2 state updates like that as it will introduce a useless second render.
If you need to set portion of the state based on another portion of the state, you can calculate it and store it outside the return statement inside a variable and used it where you need it.
In your case it might look something like this:
componentDidMount() {
this.setState(prevState => {
const nextJobAdvertisementId = [
...prevState.filters.jobAdvertisementId,
{
value: this.props.router.query.value,
id: this.props.router.query.id
}
];
return {
filters: {
jobAdvertisementId: nextJobAdvertisementId
},
resumeCollection: prevState.resumeCollection.filter(
resume => resume.jobAdvertisementId === nextJobAdvertisementId[0].id
)
};
});
}
Upvotes: 1
Reputation: 4859
Yes you can add another setState as a part of callback to the first setState(), when you want to set another state based on first.
In the below example I set 'b' state based on state 'a':
e.g
const setB = () => {
if(this.state.a)
this.setState({b:"Success"})
else
this.setState({b:"failure"})
}
this.setState({a:true},this.setB)
Upvotes: 0