Hi I Use a Function to get Date from Dayjs and I should set the value of Date in my state, but it’s giving me that Error(the Error I Mentioned in my Title), it’s necessary to, save the Value Of date in State because I want to POST it to Server and value of Day and Index are variable and for easy understanding to what I Exactly did, I simplified my code. how can I do what I want?
This is my Code :
const UserAboutPage = ( ) => {
const [Day, setDay] = useState(2);
const [Index, setindex] = useState(0);
const [TicketDay, setTicketDay] = useState();
const HandleDayDate = (Day, index) => {
const CopyList ;
const month = dayjs().month();
const year = dayjs().year();
const CurrentDayVal = dayjs().date();
const nextTicket = Math.abs(CurrentDay - Day)
if (Day == CurrentDay) {
CopyList = dayjs().calendar('jalali').locale('fa').valueOf()
setTicketDay(CopyList)
return dayjs().calendar('jalali').locale('fa').format('dddd DD-MM')
} else {
if (Day < CurrentDay || Day === 6) {
var between = 7 - nextTicket
CopyList = dayjs(new Date(year, month, CurrentDayVal + between)).calendar('jalali').locale('fa').valueOf()
setTicketDay(CopyList)
return dayjs(new Date(year, month, CurrentDayVal + between)).calendar('jalali').locale('fa').format('dddd DD-MM');
} else if (Day > CurrentDay) {
CopyList = dayjs(new Date(year, month, CurrentDayVal + nextTicket)).calendar('jalali').locale('fa').valueOf()
setTicketDay(CopyList)
return dayjs(new Date(year, month, CurrentDayVal + nextTicket)).calendar('jalali').locale('fa').format('dddd DD-MM');
}
}
}
return (
<div className="flex">
<span className="text-gray-500 mr-2">
{HandleDayDate(Day, index)}
</span>
<span className="text-green-500">
your Date :
</span>
</div>
)
}
the User Chose Index And Day By Click On Button
>Solution :
The problem you are having is that you’ve created an infinite loop of renders.
It’s a common pitfall in React and is something to look out for.
What happens is the following:
- You’re calling the
HandleDayDatefunction in the template. HandleDayDate, in turn, updates the state.- The component is re-rendered due to the state update.
- The template is re-assigned and calls
HandleDayDateagain.
And this cycle repeats, creating an infinite loop.
Typically, when faced with an infinite loop, the browser would freeze.
The error you are getting is due to React "catching" the problem and prevents the freeze.