I have a react FC. What I noticed is that when I use regular variables those variables won't get updated.
Example:
const GameItem = () => {
const { id } = useParams();
let isFollowing = false;
let gg = null;
useEffect(() => {
try {
(async function fetchGameGroup() {
const { payload } = await getAGameGroup(Number(id));
const { isFollower, gameGroup } = payload;
isFollowing = isFollower; <-========= THIS SHOULD UPDATE AFTER COMPONENT DID MOUNT
gg = gameGroup; <-========= THIS SHOULD UPDATE AFTER COMPONENT DID MOUNT
})();
} catch (error) {
console.log(error);
}
}, []);
return (
<div>
<h1>
{' '}
GAME ITEM {id} {gg} {isFollowing}
</h1>
</div>
);
};
Why is gg
and isFollowing
not showing anything? I still have a reference to gg
and isFollowing
- how come the closure here is not working?
To fix that above issue I used useState
like:
const GameItem = () => {
const { id } = useParams();
const [isFollowerState, setFollowing] = useState(false);
const [gameGroupState, setGameGroup] = useState({
id: '',
description: '',
title: '',
createdAt: '',
usersGameGroup: []
});
useEffect(() => {
try {
(async function fetchGameGroup() {
const { payload } = await getAGameGroup(Number(id));
const { isFollower, gameGroup } = payload;
setFollowing(isFollower);
setGameGroup(gameGroup);
})();
} catch (error) {
console.log(error);
}
}, []);
return (
<div>
{JSON.stringify(gameGroupState, null) <========== WORKING
{gameGroupState} <============== NOT WORKING
{}
<h1>
{' '}
GAME ITEM {id} {isFollowerState.toString()}{' '}
</h1>
</div>
);
};
but I have an issue though, the gameGroupState
won't display as is, I just want to check whats the response. I have to use JSON.stringify
why can't I just display it?