0

I need to change the state and use it but isn't possible and i don't now whhy !!!!

    const [valid, setValid] = useState(false)

    let emailsApplied = []

    candidatures.map(c => {
        emailsApplied.push(c.email)
    })


    let emailSession = ''

    if(session){
        emailSession = session.email
    }

    if(emailsApplied.includes(emailSession)) {
        setValid(true)
    }
Camille
  • 57
  • 4
  • 1
    This error happens when you unconditionally call `setValid` like you are doing here. Call `setState` only inside a sufficiently strict `useEffect` or event handler to prevent it from immediately triggering another render. – mousetail Jul 13 '22 at 09:53
  • Why does `valid` even need to be a state? It it's not modified inside a event handler it can be a normal variable – mousetail Jul 13 '22 at 09:55
  • the section of `if(emailsApplied.includes(emailSession)) { setValid(true) }` is being called inside the function component body that is forceing React to re-invoke the function again with the same props, which is calling the state setter again, which triggers React to call your function again.... and so on. similar stack overflow case [here](https://stackoverflow.com/questions/55265604/uncaught-invariant-violation-too-many-re-renders-react-limits-the-number-of-re) – Omar Dieh Jul 13 '22 at 09:57
  • My useEffect don't change the state like that : useEffect(() => { // ️ some condition here if(emailsApplied.includes(emailSession)) { setValid(true) } }, [valid]) console.log(valid) – Camille Jul 13 '22 at 10:00

1 Answers1

1

You can use function inside useState to caculate default value for state

const [valid, setValid] = useState(() => {
    let emailsApplied = []
    candidatures.map(c => {
        emailsApplied.push(c.email)
    })
    let emailSession = ''
    if(session){
        emailSession = session.email
    }
    if(emailsApplied.includes(emailSession)) return true;
    return false;
})
iamhuynq
  • 5,357
  • 1
  • 13
  • 36