So, I am creating a select month and date View in react native. I have to change the date dynamically based on the month selected so that the user can't select a date like 31st Feb. So I have created two states namely month
and dateList
storing month and list of dates and i am updating this dateList
state as soon as the user changes the month. The problem is that the inside return statement we already render the two states and the updated date state shows in the next render and not in the same render.
return (
<View style={{flexDirection : "row"}}>
<View style={styles.setTime}>
<CustomFilterMenu list={months} onPress={changeDate} item={month} setItem= {setMonth}/>
</View>
<View style={styles.setTime}>
<CustomFilterMenu list={dateList} item={date} setItem={setDate} />
</View>
</View>
)
const changeDate = () => {
setDateList(getDateArray(month));
}
Here all the functions are working well. getDateArray()
is a helper function that returns the date array required. Here dateList
, data
, month
are all the react useStates.
So what is actually happening is that this component is first triggered to render which renders the date according to dateList
data. So this date View is rendered now. Now if i change the month state, it triggers the changeDate()
function which in turn changes the dateList
array. However this change happens after everything is rendered. So, it doesn't show up any changes in the date View just now. However when i again change the month, it causes re render and now the date array corresponding to the previous dateList
array is shown. So basically the date
View is one render behind the month
View.
Can you tell me any other way to do this because i don't think this is gonna working this way. Thank you.