Reputation: 337
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
Upvotes: 0
Views: 179
Reputation: 2525
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:
HandleDayDate
function in the template.HandleDayDate
, in turn, updates the state.HandleDayDate
again.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.
Upvotes: 2
Reputation: 2363
You can't call a function with setState inside the render method {HandleDayDate(Day, index)}
Because everytime react renders it will call the function which will inturn call the setState
method causing another re-render.
So your code will go into an infinite loop.
Bring out the logic of setState
outside the function
Upvotes: 1