I need to use a callback function, immediately after state hook gets updated.
Before hooks I could do this in a very simple fashion, as following:
myFunction= () => {
this.setState({
something: "something"
}, () => {
// do something with this.state
})
}
Here is my code:
const EmployeeDetails = () =>
const [state, setState] = useState({
employee: undefined,
companyDocuments: undefined,
personalDocuments: undefined,
});
useEffect(() => {
const fetchData = async () => {
axios
.all([
await axios.get("someUrl"),
await axios.get("someUrl"),
await axios.get("someUrl"),
])
.then(
axios.spread((...responses) => {
setState({
employee: responses[0].data,
companyDocuments: responses[1].data,
personalDocuments: responses[2].data,
});
})
)
.catch(errors => {});
};
fetchData()
.then(processMyEmployee); // should be called something like this
}, []);
const processMyEmployee= () => {
// crash because state.employee is not fetched yet
}
return (
<div>it works!</div>
);
};
I've seen some other suggestions on stack, most of them imply using custom hooks, but I believe this is a common problem and therefore must be a common solution to solve it.