0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
aRtoo
  • 1,686
  • 2
  • 18
  • 38
  • Plain objects alone can't be rendered, React doesn't know what to do with them - either use `JSON.stringify`, or make your own function that iterates over the object properties and values to display them as needed. – CertainPerformance Sep 03 '20 at 02:51
  • What if we dont what the data type is? it maybe a string, number, object, or an array. – aRtoo Sep 03 '20 at 03:01
  • `JSON.stringify` is a fine choice then, since it can serialize any type of value (which isn't circular) – CertainPerformance Sep 03 '20 at 03:02

0 Answers0