0

In the example below, my groupData returns the correct set of data, but when I set the group, even after the .then(), the log for groups returns undefined. Am I using useEffect improperly? Additionally, when I set the second argument of the useEffect() to group, the log for groups does show the correct value, but obviously repeats the useEffect() over and over.

export const InvitePage = (props: any) => {
    const [group, setGroup] = useState<Group | undefined>();
    const [loading, setLoading] = useState(true);

    const getInviteKeyFromURL = () => {
        return props.location.search.split('=')[1];
    };
    const [inviteKey, setInviteKey] = useState(getInviteKeyFromURL());

    useEffect(() => {
        Groups.getGroupPreview(
            {},
            {
                groupInviteKey: inviteKey,
            },
        )
            .then((groupData) => {
                console.log('the result', groupData);
                setGroup(groupData);
            })
            .then(() => {
                console.log('group set', group);
                setLoading(false);
            });
    }, []);
}
  • TL;DR The `group` state value is `const` for the duration of the render cycle it's declared in, which means it also remains const in any callback enclosures from the render cycle, in other words, it is and always will be the same value within the `useEffect` callback scope for each time the effect callback is triggered. You should just log state updates in a separate `useEffect`. Also, set the `loading` state false in a `.finally` block to also set it in the case of any Promise rejections. – Drew Reese Jan 30 '21 at 19:52
  • No, although [group, setGroup] pair is constant but they are mutable themeself. – Behnam Esmaili Jan 30 '21 at 19:53

0 Answers0