How to use dateSetAction() and dismissedAction() methods in DatePickerAndroid? - reactjs

The documentation is not enough to understand nor there is any example to understand. Why & how to use dateSetAction() and dismissedAction() methods in DatePickerAndroid?

These are basically internal getter functions/methods that are called internally to determine whether the date has been selected or not. These two methods are defined in the DatePickerAndroid class as:
static get dateSetAction() {
return 'dateSetAction';
}
static get dismissedAction() {
return 'dismissedAction';
}
You can visit this page to populate yourself about these methods.

Simple explanation:
dateSetAction is a type of action that tells you the date has been selected in the datepicker.
dismissedAction is also another type of action that tells you the datepicker dialog has been dismissed/closed.
Example:
async openAndroidDatePicker() {
try {
const {action, year, month, day} = await DatePickerAndroid.open({
date: new Date(2020, 4, 25)
});
if (action === DatePickerAndroid.dismissedAction) {
console.log('Date picker has been dismissed/closed');
} else if (action === DatePickerAndroid.dateSetAction) {
console.log('Date has been selected');
}
} catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}

If the user picked a date, Object containing action, year, month (0-11), day. If the user dismissed the dialog, the Promise will still be resolved with the action being DatePickerAndroid.dismissedAction and all the other keys being undefined. Always check whether the action before reading the values.
async openAndroidDatePicker() {
try {
const {action, year, month, day} = await DatePickerAndroid.open({
// Use `new Date()` for current date.
// May 25 2020. Month 0 is January.
date: new Date(2020, 4, 25)
});
if (action !== DatePickerAndroid.dismissedAction) {
// Selected year, month (0-11), day
}
} catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}

Related

Lightening component recordUpdated method binding triggers stale data event

I've a lightening component which will call a controller method on update action. Below is the code of the component, controller and helper:
Component code:
<force:recordData aura:id="forceRecord"
recordId="{!v.recordId}"
layoutType="FULL"
targetRecord="{!v._record}"
targetFields="{!v.simpleRecord}"
targetError="{!v._error}"
mode="EDIT"
recordUpdated="{!c.recordUpdated}" />
Controller code:
({
doInit : function(component, event, helper) {
helper.checkStatus(component,event,helper);
},
recordUpdated : function(component, event, helper) {
var changeType = event.getParams().changeType;
console.log('changeType IS: '+ changeType);
// changeType = LOADED -- when record is created.
if (changeType === "ERROR") { /* handle error; do this first! */ }
else if (changeType === "LOADED") {
}
else if (changeType === "REMOVED") { /* handle record removal */ }
else if (changeType === "CHANGED") {
var recordId = component.get("v.recordId");
console.log('Updated record Id: '+ recordId);
helper.callAnotherMethod(component, event, helper);
}
}
})
Assume that I'm accessing payment (Id in URL: a001l000005JP5mAAG) page in the browser and modified some field in it and saved it. recordUpdated method is called and it enters CHANGED if condition.
I open some other payment (Id in URL: a001l000005HK5mBBK) in the same browser window and modify a field value in this payment and save it. At this moment recordUpdated method is called twice once for the old payment and once for the new payment.
If I look at the browser console I see the log as below:
changeType IS: CHANGED
Updated record Id: a001l000005JP5mAAG
changeType IS: CHANGED
Updated record Id: a001l000005HK5mBBK
Not sure why it is calling twice and how to stop it? Can anybody explain me why it acting like that and how to stop it?
Surprisingly if I open more payments in the same browser window and modify them it keeps adding recordUpdated event for the current payment updated and also calls update event of earlier payments with their Id.
After lot of research and deliberation, I understood that this is an issue with event listeners being added but not removed if multiple same object types are viewed and events generated in the same browser window.
I found that even though multiple events raised but if I check the changed fields in those events they will not have any data except the one changed in the current instance, hence I started checking changed fields as shown below and if they don't have any elements in the changed object then I'm moving on.
recordUpdated : function(component, event, helper) {
var changeType = event.getParams().changeType;
var changedFields = event.getParams().changedFields;
console.log('changeType IS: '+ changeType);
// changeType = LOADED -- when record is created.
if (changeType === "ERROR") { /* handle error; do this first! */ }
else if (changeType === "LOADED") {
}
else if (changeType === "REMOVED") { /* handle record removal */ }
else if (changeType === "CHANGED") {
if (Object.keys(changedFields).length == 1
&& Object.keys(Object.values(changedFields)[0])[0] == 'SystemModstamp')
{
// this is a case where nothing modified but due to issue in lightning event handlers all the
// previous events are fired along with the current event, hence avoiding action on such events.
}
else
{
var recordId = component.get("v.recordId");
console.log('To be updated record Id: '+ recordId);
console.log('changedFields: '+ JSON.stringify(changedFields));
helper.callAnyMethod(component, event, helper);
}
}
},
destoryCmp : function (component, event, helper) {
component.destroy();
},
})
This solved issue for me. Hope this might help if anyone else faces similar issue.

moment js gets current time but not the created time

I'm trying to retrieve the created_at time
but instead it renders the current time. which is not what i want.
I'm using laravel 5.5 in conjunction with moment.js
<p> <% post.created_at | phpDate : "human" %></p>
main.js
app.filter('phpDate', function() {
// A filter declaration should return an anonymous function.
// The first argument is the input passed to the filter
// Any additional arguments are paramaters passed AFTER the filter name
return function(input, format) {
// Create an instance of Moment. Use both the
// date value and timezone information PHP sent
var date = moment.tz(input.date, input.timezone);
if (format == "human") {
// Special case for formatting. If user asks for "human" format
// return a value like "13 minutes ago" or "2 weeks ago" etc.
return moment().subtract(1, 'days').calendar();
} else {
// Covert the moment to a string using the passed format
// If nothing is passed, uses default JavaScript date format
return moment().format('lll');
}
};
});
with the help of a highly respectable user on this site we were able to fix it, just needed add input within moment parathesis.
app.filter('phpDate', function() {
return function(input, format) {
if (format == "human") {
// add input then it works
return moment(input).subtract(1, 'days').calendar();
} else {
return moment().format('lll');
}
};
});

react-datetime-YouCanBookMe error time and update state

I'using this library for react time picker: https://github.com/YouCanBookMe/react-datetime
But now I have 2 problems.
The time (Am, Pm, HH:mm) in timepicker doesnt'work , because it doesn't change, it remain to 12 : 00 AM
How correctly update state? because if I handle onChange (input manual write), it receive string, that I can't parse and it is invalid date.
My code is:
import DateTime from 'react-datetime';
var moment = require('moment');
handleChangeDate(propertyName, date) {
const event = Object.assign({}, this.state.event);
if (typeof date === 'string') {
date = moment(date);
}
event[propertyName] = data.format('DD/MM/YYYY HH:mm');
this.setState({ event: event });
}
and in Render() I have compoment:
<DateTime dateFormat={"dddd, MMM. Do YYYY, HH:mm (hh:mm a)"} value={this.state.event.to} onChange={this.handleChangeDate.bind(this, 'to')}/>
What is wrong?
check in below link.
Customized calendar will solve your problem.
https://github.com/YouCanBookMe/react-datetime#customize-the-appearance
After choose date in calendar then click on date. It will show the edit option for time.
Example Link
https://codepen.io/simeg/pen/YppLmO
Let it try

Restrict post dates into Full Calendar

I´m developing Full Calendar like this, but instead of creating events I just get it from the database.
So now I developing Backend to receive days of the week of an event like this:
As you can see I receive booleans within days of the week
Now I want to restrict if one of this days come false, calendar doesn´t allow me to do that
JS Function:
function isGreaterThanToday(date) {
return date < hoy ? false : true;
}
function updateAssignedEvent(event, delta, revertFunc) {
if (!isGreaterThanToday(event.start)) {
mostrarError("Cant post an event today or before today.");
revertFunc();
return;
}
event.start = $.fullCalendar.moment(moment($.fullCalendar.moment(event.start.format())._i));
event.end = event.end ? $.fullCalendar.moment(moment($.fullCalendar.moment(event.end.format())._i)) : event.start;
event.color = getTareaCalendarioColor(event.tipoResponsable,
event.estatusTarea,
event.start,
event.end.diff(event.start, 'hours') <= 24 ? event.start : event.end);
updateEvent(event).then(function(data) {
if (!data.success) {
revertFunc();
return;
}
event.end = event.end !== event.start ? event.end.add(1, 'day') : event.end;
$calendar.fullCalendar('updateEvent', event);
}, function(error) {
revertFunc();
});
}
As you can see I have a function calledfunction isGreaterThanToday(date), I use it to restrict post an event today or before today. I want to do something like this, but I don´t have an idea of how can I call these booleans and compare for example Sunday of the calendar with Sunday of boolean receive. Can anyone help me there? Regards
For example into my function I add:
if (event.accion.agendarDomingo != true) {
mostrarError("Sunday is not allowed");
revertFunc();
return;
}
But how can I compare with my event.start and event.end DAY?
To get day of week using moment.js use 'e' as a format. result will be 0..6 Monday to Sunday.
event.start.format('e');
To check if the time is passed use isAfter function:
If nothing is passed to moment#isAfter, it will default to the current time.
moment(event.start).isAfter();
Now these two validation constraints combined would look like this:
function isDateValid(date) {
return date.format('e') !== "6" && moment(date).isAfter();
}

jest enzyme reactJS - method executes regardless of return

I have the following method I want to test:
handleDayClick(e, day, {disabled}) {
if (disabled) {
// Do not update the state if the day is disabled
return;
}
this.setState({ selectedDay: day });
this.props.dateClick(day);
};
So I wrote a mock function, passed it as a prop and figured I would test state and if the function gets called:
it('handleDayClick() should NOT set state.selectedDay, call props.dateClick when disabled', () => {
let mockDateClick = jest.fn();
const sidebar = shallow(<Sidebar dateClick={mockDateClick}/>);
let e = 'whatever';
let day = 'tomorrow';
sidebar.instance().handleDayClick(e, day, true);
expect(sidebar.state().selectedDay).toBe(undefined);
expect(mockDateClick).toNotHaveBeenCalled();
});
The thing is that the state().selectedDay gets set to tomorrow. The value before calling the method is 2017-01-12T18:18:13.216Z, so I am pretty sure the method does not exit on the render function.
What am I doing wrong?
In your test, you are doing: sidebar.instance().handleDayClick(e, day, true);
while handleDayClick is destructuring an object with the disabled key
handleDayClick(e, day, {disabled}) {
}
Try to call it like this : sidebar.instance().handleDayClick(e, day, { disabled: true });
In the future you might want to use tools like Flow to prevent errors https://flowtype.org/docs/react.html
you would have been able to detect it earlier by doing something like this :
handleDayClick(e: {}, day: string, {disabled}: boolean) {
}

Resources