Agenda - dynamically change selected day - react-native

I'm having trouble to dynamically change the selected day. For example, I want to change selected day to today when leaving the screen; I don't want to have other selected day than today when leaving... How can I do that? I'm using the agenda.
Also, I want to change the selected day when the user clicks on some button in that screen. My agenda list date is not changed at all if I just set the state for selectedDay...
My code for now;
componentDidMount() {
this.props.navigation.addListener('didBlur', (playload)=>{
console.log(playload);
this.onDayPress(Moment().format('YYYY-MM-DD').toString());
});
}
My agenda:
<Agenda
// the list of items that have to be displayed in agenda. If you want to render item as empty date
// the value of date key kas to be an empty array []. If there exists no value for date key it is
// considered that the date in question is not yet loaded
items={this.state.items2}
// callback that gets called when items for a certain month should be loaded (month became visible)
//loadItemsForMonth={}
// callback that fires when the calendar is opened or closed
onCalendarToggled={(calendarOpened) => {}}
// callback that gets called on day press
onDayPress={this.onDayPress.bind(this)}
// callback that gets called when day changes while scrolling agenda list
onDayChange={(day)=>{
this.setState({day: day})
console.log('OnDayChange: ' + day);
}}
// initially selected day
//selected={ Moment().format('YYYY-MM-DD').toString()}
//selected={'2018-02-20'}
selected={this.state.selectedDay}
// Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
minDate={this.state.minDate}
// Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
maxDate={this.state.maxDate}
...
onDayPress method;
onDayPress(day) {
//console.log('Predn zamenjam selected day: ' + this.state.selectedDay);
if(day.dateString === undefined) {
if(day !== undefined) {
//console.log('day: ' + day);
this.setState({
selectedDay: day
});
return true;
}
}
this.setState({
selectedDay: day.dateString
});
this.getNextThreeDays(day.dateString);
this.getQuotes(day.dateString);
}
Environment
npm ls react-native-calendars: 1.19.4
npm ls react-native: ^0.55.4

Few years late but managed to solve this using refs
import React, { createRef } from 'react';
const agendaRef = createRef();
When rendering the agenda include the reference
<Agenda
ref={agendaRef}
...
/>
For the onPress function for the button include the call to chooseDay
const date = '2020-10-01' // the date you want to go to
agendaRef.current.chooseDay(date)
It should animate as if the date button was tapped

Related

React Native: App get stuck in computing a simple loop on dates using moment

I am developing an app using RN which deals a lot with dates. I have a helper function to calculate an array of dates which are the beginnings of weeks between two given dates. I call this helper method in the useEffect function of my screen name SelectWeek. Here is my function:
static getWeeks(unixTime) {
const result = [];
const createdTime = moment(
moment(unixTime, "X").format("YYYY-MM-DD"),
"YYYY-MM-DD"
);
const today = moment(new Date()).add(8, "days");
let temp = createdTime;
while (temp.format("X") < today.format("X")) {
result.push(temp.format("jYYYY-jMM-jDD"));
temp = temp.endOf("week").add(1, "minutes");
}
return result;
}
export default function SelectWeek(props) {
useEffect(() => {
const listWeek = TimeHelper.getWeeks(createdTime);
console.log(listWeek);
}, []);
return ( // some jsx code )
}
The app works fine if the number of weeks is small. But when I add more days to my second date (today), for example if I add 80 days instead of 8, when I want to mount the SelectWeek screen the app freeze and the screen is not mounted. Also the phone start overheating instantly.
Any suggestion?

vuejs datepicker selected event is no working properly

I'am vuejs-datepicker . I'm trying to print the selected date which is stored in a variable in data. Initially the value of the variable is empty. vuejs-datepicker supports the selected event. so when the event is triggering, I mean if date is selected the selected event get triggered. but does not print ta current selected date rather it print empty string. if I again select another date the it prints the previous date. It is printing the the previous stored date. code is given below
Uses
<date-picker :bootstrap-styling="true" class="datepicker form-control"
placeholder="Select Date" v-model="appointment.appointmet_date"
#selected="dateSelected()"></date-picker>
dateSelected method
dateSelected () {
console.log(this.appointment.appointmet_date)
},
data property
data () {
return {
appointment: {
appointmet_date: '',
}
}
}
When I entered first date it printed null. when I entered date second time it printed the time entered first time
upadate
dateSelected () {
// console.log(this.appointment.appointmet_date)
var self = this
this.$nextTick(() => console.log(self.appointment.appointmet_date))
this.$http.post(apiDomain + 'api/getAvailableDate', {avlDate: self.appointment.appointmet_date})
.then(response => {
console.log(response)
})
}
when i entered first date it printed null. when i entered date second time it printed the time entered first time
Yes because the selected event is fired before the Vue nextTick function which updates the v-model.
Please below code and working codesandbox demo.
dateSelected (e) {
console.log(this.appointment.appointmet_date);
this.$nextTick(() => console.log(this.appointment.appointmet_date))
},
For future visitors - simply make the post request within the Vue nextTick() like so:
dateSelected () {
...
this.$nextTick(() => {/* post call here */})
}

How to run a function for certain period of time in react-native?

I made a counter component using touchableopacity,
What I want to do is keep adding 1 until user holds the button and stop when they leave it,
I also want to just add 1 when user taps the add button.
What I have tried is I started a loop on pressIn with a time interval so the whole process looks good but I couldn't stop the loop on pressout
This is resolved,
What I did is onPressIn called my add function inside an interval of 500 and onpressout cleared that interval
Here is the code snippet for better understanding
add = () => {
this.setState(p=>{
return{
...p,
number:p.number + 1
}
})
}
addLoop = () => {
this.addInterval = setInterval(this.add,500)
}
stopAdding = () => {
clearInterval(this.addInterval)
}
and in my touchableOpacity called it like this
onPressOut={this.stopAdding} onPressIn={this.addLoop} onPress={this.add}

DataTables does not save state of date range search

I am using data tables to display a list of events of different types. Besides the default global text search I need to
1. filter list by event type
2. filter list by date range (show only today -> infinity)
3. Save the state of the table for the the current session.
The state saves as expected except for the date range search which is always reset. Am I missing something or custom search functions are out of the scope of state saving? Here's the relevant code in jQuery:
Fist I add my own search function through the provided method. This works except it's state is not saved
// Extend search()
var threshold_timestamp = xxxxxxxxxxxx // set for beginning of today)
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex) {
var timestamp = parseInt(data[1]); // event date timestamp
if (timestamp > threshold_timestamp) {
return true;
}
return false;
}
);
Then I add a listeners for the select used to switch between the event type options ('','Event','Sports','Dance'...) and the button user to turn on/off the date range filter
$('#filter-by-type').on('change', function() {
table.columns(0).search( $(this).val() ).draw();
});
$('#dt-history').on('click', function() {
// Logic to toggle threshold_timestamp between 0 or value
table.draw();
});
Then I call DataTables
var table = $('#example').DataTable( {
ajax: "datasource.json",
stateSave : true,
stateDuration: -1,
columns: [
{ data: "type"}, //str as 'Sport','Dance'
{ data: "date"} // int as 1528572000
]
});
I managed to scratch my head sideways and "save the date search" using localstorage but that is a hack. On page load I trigger a button click to execute the search so initially the tables seems empty, the "No data available in table" message appears and then the filtered results display. As a second hack I will suppress that message so when there will really be no data... there will be no message :(

how to add minutes to Date() in react-native?

I want to add 5 minutes to current time and store it to this.state.date.
However,
this.setState({
date: new Date() + new Date(0,0,0,0,0,5,0),
});
gives me some strange error, saying
`props.date.getTime is not a function. (In 'props.date.getTime()', 'props.date.getTime' is undefined)
DatePickerIOS_render
DatePickerIOS.ios.js:125
EDITED: According to this post I also tried below,
this.setState({
date: this.state.date.setMinutes((new Date()).getMinutes()+5)
});
but it still gives me the same error message. What is the correct way to add minutes to Date() in react-native?
Btw, I'm using datepickerios on another part of the app, and not sure why the error is related to DatePickerIOS.ios.js in the first place. The other part of the app which actually uses the DatePickerIOS works fine without error.
EDITED AGAIN:
Below is the full function. This function is called from a SegmentedControlIOS which has values ['5min from now', '15min from now', '30min from now', 'custom'].
_onTimeChange = (event) => {
switch (event.nativeEvent.selectedSegmentIndex) {
case 0:
// 5min
return this.setState({
date: this.state.date.setMinutes((new Date()).getMinutes()+5),
time: this.state.date.toLocaleTimeString()
});
case 1:
// 15min
return this.setState({
date: this.state.date.setMinutes((new Date()).getMinutes()+15),
time: this.state.date.toLocaleTimeString()
});
case 2:
// 30min
return this.setState({
date: this.state.date.setMinutes((new Date()).getMinutes()+30),
time: this.state.date.toLocaleTimeString()
});
case 3:
// show modal with datepicker (this one works fine)
return this.setModalVisible(true);
}
}
What happens: If I change selection from the segmented control once, a yellow warning bar with props error message is shown at the bottom of my simulator. If I change selection once again, then the red screen shows up with '_this5.state.date.setMinutes is not a function'.
So it looks like
date: this.state.date.setMinutes((new Date()).getMinutes()+5)
does add minutes, but when I do it twice it ends up in error.
Please help!
Try this:
var d = new Date(); // get current date
d.setHours(d.getHours(),d.getMinutes()+5,0,0);
EDIT
var d = new Date(); // get current date
d.setHours(d.getHours(),d.getMinutes()+5,0,0);
this.setState(date:d,time:d.toLocaleTimeString());