Skip to content

Commit c46a3ab

Browse files
julialbqtalyssonoc
andauthored
Refactor AsyncForm class to function component component (#989)
* refactor: AsyncForm class to function component * refactor: wrap handleSubmit in useCallback according to reviewer suggestion --------- Co-authored-by: Talysson de Oliveira Cassiano <[email protected]>
1 parent 5d77176 commit c46a3ab

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed
Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,23 @@
1-
import React from 'react';
1+
import { useCallback, useState } from 'react';
22

3-
class AsyncForm extends React.Component {
4-
constructor(props) {
5-
super(props);
6-
this.state = { loading: false };
7-
this._handleSubmit = this._handleSubmit.bind(this);
8-
}
3+
const AsyncForm = ({ onSubmit, getFormData, children }) => {
4+
const [loading, setLoading] = useState(false);
95

10-
_handleSubmit(ev) {
11-
ev.preventDefault();
12-
this.setState({ loading: true });
13-
this.props
14-
.onSubmit(this.props.getFormData())
15-
.catch(() => this.setState({ loading: false }));
16-
}
6+
const handleSubmit = useCallback(
7+
async ev => {
8+
ev.preventDefault();
9+
setLoading(true);
10+
try {
11+
await onSubmit(getFormData());
12+
setLoading(false);
13+
} catch (error) {
14+
setLoading(false);
15+
}
16+
},
17+
[onSubmit, getFormData]
18+
);
1719

18-
render() {
19-
return this.props.children({
20-
loading: this.state.loading,
21-
handleSubmit: this._handleSubmit,
22-
});
23-
}
24-
}
20+
return children({ loading, handleSubmit });
21+
};
2522

2623
export default AsyncForm;

0 commit comments

Comments
 (0)