0

In my React code below, I'm getting an error:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

If I comment out the switch statement, the error goes away. So, what in this switch statement is causing this? This all started from trying to use the useState.

const UserBillableGoals = () => {

    //Set User
    const { user } = useAuth0();
    const [goal, setGoal] = useState(0);
    const [teamMemberName, setTeamMemberName] = useState("");

    switch (user.email) {
        case "adam@example.com":
        setTeamMemberName("Adam");
        setGoal(0);
        break;
        case "andrew@example.com":
        setTeamMemberName("Andrew");
        setGoal(12000);
        break;
        case "kacye@example.com":
        setTeamMemberName("Kacye");
        setGoal(0);
        break;
        case "gabriela@example.com":
        setTeamMemberName("Gabriela");
        setGoal(17000);
        break;
        case "jazmin@example.com":
        setTeamMemberName("Jazmin");
        setGoal(14000);
        break;
        default:
        setTeamMemberName("No Name Found");
        setGoal(0);
        break;
    }

    
    
    
    return (
    <div>
      
      <div>
        <p>{year}, {month}</p>
        <p>{path}</p>
      </div>
    </div>
  );
}
Adam Norton
  • 512
  • 2
  • 5
  • 21

1 Answers1

1

React is reactive, and this is more true with functional components.

Your switch statement is changing the state of the component before it has a chance to render. Every time the state changes, the component has to re-render which triggers the switch statement again.

You can solve this by wrapping the switch with a useEffect:

useEffect(() => {
  switch (user.email) {
    case "adam@example.com":
    setTeamMemberName("Adam");
    setGoal(0);
    break;
    case "andrew@example.com":
    setTeamMemberName("Andrew");
    setGoal(12000);
    break;
    case "kacye@example.com":
    setTeamMemberName("Kacye");
    setGoal(0);
    break;
    case "gabriela@example.com":
    setTeamMemberName("Gabriela");
    setGoal(17000);
    break;
    case "jazmin@example.com":
    setTeamMemberName("Jazmin");
    setGoal(14000);
    break;
    default:
    setTeamMemberName("No Name Found");
    setGoal(0);
    break;
  }
}, []);

This ensures that the state changes only happen after the initial render

smac89
  • 39,374
  • 15
  • 132
  • 179