0

I am working on React. I am having following component

export default function ShowUsers() {
  const [users, setUsers] = React.useState([]);
  const classes = useStyles();
  // userData function returns array of components after fetching data from server with a GET request.
  // I have passed setUsers function to set the value of users after fetching from server. 
  var userData = GetUserData(classes, setUsers, users);
  useEffect(() => {
    setUsers(userData);
  }, []);
  return (
    <div style={divStyle}>
      {userData}
    </div>
  );
}

This code is calling the GetUserData function and making the GET request infinitely. Could you please help me to find what is wrong in this code and if someone can just explain the cause and solution with a little explanation, I would be greatful.

Thanks

abinash_123_
  • 47
  • 1
  • 9
  • Why are you calling `GetUserData` from the component body and not inside the `useEffect`? – Brian Thompson Jul 02 '21 at 18:27
  • `GetUserData` gets passed `setUsers` as an argument, so it's very likely that it is calling that function. If that's true, then you will get a re-render - and since you're calling `GetUserData` from the component body it will call it again - and so on infinitely. – Brian Thompson Jul 02 '21 at 18:28
  • Hi, thanks for your response. I would like to understand, how https://stackoverflow.com/a/67360797/9409824 is different than your suggestion? – abinash_123_ Jul 02 '21 at 18:31
  • Because in that answer they are only **declaring** a function in the body. You are **calling** a function in the body. – Brian Thompson Jul 02 '21 at 18:32
  • Also that answer was downvoted and has issues, so I'm not sure why it's being used as support... – Brian Thompson Jul 02 '21 at 18:32
  • So, what would be the working solution in this scenario? – abinash_123_ Jul 02 '21 at 18:36
  • Call the function from *inside* the `useEffect`. – Brian Thompson Jul 02 '21 at 18:48
  • Thanks, it works. But how would I use the userData for rendering? – abinash_123_ Jul 02 '21 at 19:46
  • You're putting it in state, just use the state const instead of the direct result of the function call. – Brian Thompson Jul 02 '21 at 19:57
  • Yes, I got your point. But actually I am not able to access the `classes, setUsers, users` variables inside the useEffect callback. – abinash_123_ Jul 02 '21 at 20:17
  • They are within scope, so there's probably something else going on here. I'm not sure what `GetUserData` does, but the code you've provided doesn't make a lot of sense.. Why pass `setUsers` and `users` to a function that returns the value you set to `users`? It seems like maybe the function does more than it needs too.. – Brian Thompson Jul 02 '21 at 20:38

0 Answers0