Camille
Camille

Reputation: 57

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop with my useState in nextjs

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)
    }

Upvotes: 0

Views: 51

Answers (1)

iamhuynq
iamhuynq

Reputation: 5529

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;
})

Upvotes: 1

Related Questions