diff options
author | Vitaly Takmazov | 2019-10-24 13:16:38 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2023-01-13 10:37:55 +0300 |
commit | 8bc4d932b20079c01045248fc02b2726ba73775c (patch) | |
tree | b05d373bb324d76c276eee12898b78ac2ea71cf8 /vnext/src/ui/UserInfo.js | |
parent | 1baee0fc63ba8228d009a11c0211dca8fbef09bf (diff) |
Correctly change state from useEffect without dependencies
Diffstat (limited to 'vnext/src/ui/UserInfo.js')
-rw-r--r-- | vnext/src/ui/UserInfo.js | 56 |
1 files changed, 30 insertions, 26 deletions
diff --git a/vnext/src/ui/UserInfo.js b/vnext/src/ui/UserInfo.js index ccdd5c04..6310b8b7 100644 --- a/vnext/src/ui/UserInfo.js +++ b/vnext/src/ui/UserInfo.js @@ -12,34 +12,35 @@ import './UserInfo.css'; let isMounted; /** - * Wrapper for dumb VSCode - * @param {import('../api').User} user - */ -function useUserState(user) { - return useState(user); -} - -/** * User info component * @param {{user: string, onUpdate?: function, children?: Element}} props */ export default function UserInfo(props) { - const [user, setUser] = useUserState({ uname: props.user, uid: 0 }); + /** @type {import('../api').User} user */ + const currentUser = { + uname: props.user, + uid: 0 + }; + const [user, setUser] = useState(currentUser); const { onUpdate } = props; useEffect(() => { isMounted = true; - if (!user.avatar) { - info(user.uname).then(response => { - if (isMounted) { - setUser(response.data); - onUpdate && onUpdate(response.data); - } - }); - } + setUser(previous => { + if (!previous.avatar) { + info(previous.uname).then(response => { + if (isMounted) { + onUpdate && onUpdate(response.data); + return response.data; + } + }); + } + return previous; + }); + return () => { isMounted = false; }; - }, [onUpdate, user, user.avatar, setUser]); + }, [onUpdate]); return ( <> <div className="userinfo"> @@ -104,17 +105,20 @@ export function UserLink(props) { const [user, setUser] = useState(props.user); useEffect(() => { isMounted = true; - if (user.uri) { - fetchUserUri(user.uri).then(response => { - if (isMounted) { - setUser(response.data); - } - }); - } + setUser(previous => { + if (previous.uri) { + fetchUserUri(previous.uri).then(response => { + if (isMounted) { + return response.data; + } + }); + } + return previous; + }); return () => { isMounted = false; }; - }, [user.uid, user.uri, setUser]); + }, []); return ( user.uid ? <Link key={user.uid} to={`/${user.uname}/`} className="info-avatar"><img src={user.avatar} />{user.uname}</Link> |