I am beginner in react hooks, i am also using graphql in my project. Someone can help in converting a component to react hooks.
class Detail extends Component {
static propTypes = {
classes: PropTypes.shape(commonStyles).isRequired,
siteId: PropTypes.string
};
state = {
showDialog: false
};
handleRowHistory = () => {
this.setState({ showDialog: true });
};
render() {
const { showDialog } = this.state;
const { data, classes, siteId } = this.props;
if (data.error) {
return <CardErrorIndicator apolloData={data} />;
} else if (data.loading) {
return <CardLoadingIndicator />;
}
const { sites } = data;
const { controller } = _.first(sites);
return (
<div
className={classNames(
classes.overall,
classes.basePadding,
"site-assets-detail-page"
)}
>
<SiteRowController
controller={controller}
onRowHistoryClick={this.handleRowHistory}
/>
{showDialog && (
<RowHistoryDialog
open={showDialog}
siteId={siteId}
onClose={() => this.setState({ showDialog: false })}
/>
)}
</div>
);
}
}
const DetailWithData = compose(
graphql(SITE_ASSETS_DETAIL_QUERY, {
options: props => ({
variables: {
siteId: props.siteId
},
pollInterval: 5000
})
})
)(Detail);
export default withStyles(commonStyles)(DetailWithData);
I understand that React-Hooks is alternative to React Class style. The question is if I can refactor and add React hooks into this.
Thanks
Brian Le :
The only 2 hooks you need to know in this case are useState() and useCallback() (optionally). For the prop types you can declare them separately. So combine all these your code should look roughly like this:\n\nconst Detail = ({ data, classes, siteId }) => {\n const [showDialog, setShowDialog] = useState(false);\n const handleRowHistory = () => {\n setShowDialog(true);\n }; // You might need to use useCallback to stop new functions from being created\n\n if (data.error) {\n return <ErrorComponent />;\n }\n if (data.loading) {\n return <LoadingComponent />;\n }\n\n return <YourComponent />;\n};\n\nDetails.propTypes = {\n // Declare your prop types here\n};\n\n\nYou might want to check out React docs for hooks for further reference.",
2019-04-11T07:27:45