I want to redirect the page if the length of props.fields is zero. But the problem it is getting rendered twice so when the it is empty it gets redirected and doesn't wait for the second time. I am new to React, it would be great if someone could help me.I have spent hours on fixing this.
import React, { Component, useEffect, useState } from 'react'
import Field from './field'
import {Redirect} from 'react-router-dom'
export default function FieldList(props) {
const [redirect,setRedirect] = useState(false);
useEffect(()=>{
if(props.fields.length===0) {
setRedirect(true)
}
else
setRedirect(false)
},[props.fields])
return (
<div>
<h1 style={{textAlign:"center", margin:"20px 0"}}>{props.text}</h1>
<div className='field-list'>
{props.fields.map((name) => (
<Field name={name} />
))}
</div>
{redirect && <Redirect to={'/'} />}
</div>
)
}