I've just started working with React, and wrote a couple of HOCs. Then I read that Functional Components and hooks are the suggested way of moving forward, so I decided to rewrite my HOCs.
A common pattern I used was:
class MyButton(Component) {
...
handleClick = () => {
setState({busy: True}, () => {
fetchAPI().then(
(results) => {
setState({results: results, errs: [], busy: False});
},
(err) => {
setState({errs: err, busy: False});
});
});
};
render() {
return(
<Button disabled={this.state.busy} onClick={this.handleClick} />
)
}
}
If I understand correctly, when I click the button, it would disable it, render the disabled button, then fetch things from the api, then set the state with the results (and enable the button), then render the enabled button.
This would prevent people from clicking the button 10 times, hitting the api 10 times before the first is finished.
How do I do this with functional components and hooks? My naive implementation would be this, but it seems incorrect.
MyButton = (props) => {
const [results, setResults] = useState([]);
const [errs, setErrs] = useState([]);
const [busy, setBusy] = useState(False);
const handleClick = () => {
setBusy(true);
fetchAPI().then(
(results) => {
setResults(results);
setErrs([]);
setBusy(False);
},
(err) => {
setErrs(errs);
setBusy(False);
});
);
}
return (
<Button disabled={busy} onClick={handleClick} />
)
}
Is there a better way?