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 )
});
}
)
)
}
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
)
};
});
}