From 8bc4d932b20079c01045248fc02b2726ba73775c Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 24 Oct 2019 13:16:38 +0300 Subject: Correctly change state from useEffect without dependencies --- vnext/src/ui/Thread.js | 19 +++++++++------- vnext/src/ui/UserInfo.js | 56 ++++++++++++++++++++++++++---------------------- 2 files changed, 41 insertions(+), 34 deletions(-) (limited to 'vnext/src') diff --git a/vnext/src/ui/Thread.js b/vnext/src/ui/Thread.js index cbd40c4c..2e07cd0e 100644 --- a/vnext/src/ui/Thread.js +++ b/vnext/src/ui/Thread.js @@ -46,17 +46,20 @@ function Comment({ msg, draft, visitor, active, setActive, onStartEditing, postC }, []); useEffect(() => { isMounted = true; - if (author.uri) { - fetchUserUri(author.uri).then(response => { - if (isMounted) { - setAuthor(response.data); - } - }); - } + setAuthor(previous => { + if (previous.uri) { + fetchUserUri(previous.uri).then(response => { + if (isMounted) { + return response.data; + } + }); + } + return previous; + }); return () => { isMounted = false; }; - }, [author.uri]); + }, []); return (
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 @@ -11,35 +11,36 @@ 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 ( <>
@@ -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 ? {user.uname} -- cgit v1.2.3