From e39818079a05cdd7cfc4744e972ce87105e1ff87 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 21 Feb 2019 00:02:17 +0300 Subject: Refactor Avatar using hooks --- vnext/src/components/Avatar.js | 82 ++++++++++++++++++------------------------ 1 file changed, 35 insertions(+), 47 deletions(-) (limited to 'vnext/src') diff --git a/vnext/src/components/Avatar.js b/vnext/src/components/Avatar.js index 6e56cfc29..67d75c5e1 100644 --- a/vnext/src/components/Avatar.js +++ b/vnext/src/components/Avatar.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; @@ -10,58 +10,46 @@ import { fetchUserUri } from '../api'; import './Avatar.css'; -class Avatar extends React.Component { - constructor(props) { - super(props); - this.state = { - user: props.user - }; - } - componentDidMount() { - let user = this.state.user; +let isMounted; + +function Avatar(props) { + const [user, setUser] = useState(props.user); + useEffect(() => { + isMounted = true; if (!user.uid && user.uri) { fetchUserUri(user.uri).then(response => { - this.setState({ - user: response.data - }); + if (isMounted) { + setUser(response.data); + } }); + return () => { + isMounted = false; + }; } - } - shouldComponentUpdate(nextProps, nextState) { - return this.state.user.avatar != nextState.user.avatar || this.state.user.uid != nextState.user.uid - || this.props.user.avatar != nextProps.user.avatar || this.props.user.uid != nextProps.user.uid; - } - componentDidUpdate(prevProps, prevState, shouldReload) { - this.setState({ - user: this.props.user - }); - } - render() { - let user = this.state.user; - return ( -
-
- { - user.uname ? - - {user.avatar ? - {`${user.uname}`} - : } - - : - } -
-
- - - {user.uname} + }); + return ( +
+
+ { + user.uname ? + + {user.avatar ? + {`${user.uname}`} + : } - - {this.props.children} -
+ : + } +
+
+ + + {user.uname} + + + {props.children}
- ); - } +
+ ); } export default Avatar; -- cgit v1.2.3