const { width: WIDTH } = Dimensions.get('window');
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = mm + dd + yyyy;
class Attendance extends Component {
state = {
image: null,
submit: false,
loading: false,
face: null,
confidence: 0,
class: '',
flag: ''
};
async componentDidMount() {
await Permissions.askAsync(Permissions.CAMERA);
const { currentUser } = firebase.auth();
firebase
.database()
.ref('users/')
.child(currentUser.uid)
.on('value', snap =>
this.setState({
face: snap.val().image,
class: snap.val().stream_sem
})
);
}
render(){
return(
<View style={styles.Conatiner}>
<Loader loading={this.state.loading} />
{this.renderContent()}
</View>
);
}
renderContent = () => {
firebase.database().ref('attendance')
.child(this.state.class)
.child(today)
.on("value", snap => {
this.setState({ flag: snap.val().flag});
});
if(this.state.flag === "0") {
//**something**
}
else {
//**something**
}
}
}
When i am trying to write this.state.class, it is showing reference child failed. Here is the error detail i am getting.
My firebase database Picture is here. Can you please tell where i am going wrong. I want to access "flag" part of the database. CSE8 should match with the users stream_sem
ThankYou in advance
When your renderContent is called first time, your state.class is empty string, remember that firebase snapshot will be loaded asynchronously. Also, do not attach listeners to firebase in a render function that is called by render method, you will end up having a lot of listeners.
Your logic should be something like:
Get user data from firebase
If data is not null, set state
After state is set, get attendance data from database
Set state appropriately
Always write rough algorithm before jumping state to dev (Ignore if you already knew that). Happy learning, Cheers!
Related
`Below mentioned is my code for intersection observer
useIntersectionObserver
/* eslint-disable #typescript-eslint/no-shadow */
import { RefObject, useEffect, useState } from 'react';
export default function useIntersectionObserver(
elementRef: RefObject<Element>,
{ threshold = 0, root = null, rootMargin = '0%' }
) {
const [entry, setEntry] = useState<IntersectionObserverEntry>();
const callBackFunction = ([entry]: IntersectionObserverEntry[]): void => {
setEntry(entry);
};
useEffect(() => {
const node = elementRef?.current; // DOM Ref
const isIOSupported = !!window.IntersectionObserver;
if (!isIOSupported || !node) return;
const observerOptions = { threshold, root, rootMargin };
const observer = new IntersectionObserver(
callBackFunction,
observerOptions
);
observer.observe(node);
return () => observer.disconnect();`your text`
}, [elementRef, JSON.stringify(threshold), root, rootMargin]);
return entry;
}
Below is the code mentioned where I am calling useInterSectionObserver hook
const scrollDivElementRef = useRef<null | HTMLDivElement>(null);
const chatDivRef = useRef<null | HTMLDivElement>(null);
const entry = useIntersectionObserver(scrollDivElementRef, {});
const isVisible = !!entry?.isIntersecting;
Here scrollDivElementRef is the ref of div which we are observing for the intersection.It is basically our sentinal element.
Below mentioned is the useEffect hook which is going to perform some action when isVisible will become true.
Below mentioned is a code in react-native webview ,basically we are opening our react web app inside ios app , but our intersection observer is not able to detect changes . We have implemented intersection observer for infinite loading of messages. Every time user will scroll upwards , we will get "isVisible" as true and we will make an API call to fetch more messages.
useEffect(() => {
if (isVisible) {
dispatch(
getPostsForChannel(inputChannelId, true, channelMessages[0].timestamp)
);
}
}, [isVisible]);
<View style={styles.container}>
<WebView
style={{ marginTop: 40 }}
//TODO: Update the url
source={{ uri: 'http://192.168.1.2:3000' }}
onLoad={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
}}
javaScriptEnabled={true}
onError={(e) => {
const { nativeEvent } = e;
setUrl(HOME_URL);
}}
onHttpError={() => {
setUrl(HOME_URL);
}}
onMessage={onMessage}
limitsNavigationsToAppBoundDomains={true}
// injectedJavaScript="window.octNativeApp=true"
injectedJavaScriptBeforeContentLoaded={initializeNativeApp}
scalesPageToFit={false}
setBuiltInZoomControls={false}
useWebView2
allowsInlineMediaPlayback={true}
mediaPlaybackRequiresUserAction={false}
></WebView>
</View>`
It will be really very helpful , if you people can help me with this problem.
Thanks & Regards
Mohit
I tried giving the height & width to the webview but it is also not working.Tried almost every piece of advise available in other platforms but not able to fic this`
We are seeing an issue with users unable to access our production and PPE apps via LinkedIn sign in. The redirection is not happening to specified redirect URL once users provides user name and password. The network trace shows login is successful but not going to redirect URL. This has been working last 4 years or so and suddenly started failing in both environments from yesterday.
Bummer. Something went wrong
We tried verifying the network trace and a support case is raised to LinkedIn with recording. Finally we are redirected to raise the issue here.
I had the same issue and found that it was caused by using JSON.stringify to "overload" the state parameter with other parameters. In my case, I add other parameters in the following way:
providerCfg.auth_params.state = JSON.stringify({
state: providerCfg.auth_params.state,
redirectPageUrl,
redirectParams,
userTypeBit,
isLogin
})
const authUrl = new URL(providerCfg.auth_url)
Object.entries(providerCfg.auth_params).forEach(([key, val]) => {
authUrl.searchParams.append(key, encodeURIComponent(val))
})
return buildURL(providerCfg.auth_url, providerCfg.auth_params)
When I removed the call to JSON.stringify and just passed in a state parameter, the oauth flow worked correctly. Obviously, the other parameters that I passed in were important so I created my own functions to serialize and deserialize the values. The code below works well for anything other than deeply nested objects. You will need to update the metaDataCfg based on your own requirements.
const META_STRING_DELIMITER = '|'
const serializeBasicObject = (targetObj) => {
if (!targetObj) {
return ''
}
return Object.entries(targetObj).reduce((objString, [key, val]) => {
const param = `${key}=${val || ''}`
if (!objString.length) {
return param
}
return `${objString}${META_STRING_DELIMITER}${param}`
}, '')
}
const deserializeBasicObject = (targetStr) => {
if (!targetStr) {
return ''
}
const keyValPairs = targetStr.split(META_STRING_DELIMITER)
return keyValPairs.reduce((targetObj, keyValPair) => {
const splitIdx = keyValPair.indexOf('=')
const key = keyValPair.slice(0, splitIdx)
targetObj[key] = keyValPair.slice(splitIdx + 1, keyValPair.length)
return targetObj
}, {})
}
const metaDataCfg = {
state: {},
redirectPageUrl: {},
redirectParams: {
serialize: serializeBasicObject,
deserialize: deserializeBasicObject
},
userTypeBit: { deserialize: Number },
isLogin: { deserialize: dataUtil.getBoolean }
}
const getMetaString = (metaData) => {
return Object.entries(metaDataCfg).reduce((metaString, [metaDataKey, cfg]) => {
const val = (cfg.serialize) ? cfg.serialize(metaData[metaDataKey]) : metaData[metaDataKey]
const param = `${metaDataKey}=${dataUtil.isNil(val) ? '' : val}`
if (!metaString.length) {
return param
}
return `${metaString}${META_STRING_DELIMITER}${param}`
}, '')
}
export const getDataFromMetaString = (metaString) => {
const params = metaString.split(META_STRING_DELIMITER)
const data = params.reduce((metaData, param) => {
const splitIdx = param.indexOf('=')
const key = param.slice(0, splitIdx)
let val = param.slice(splitIdx + 1, param.length)
if (dataUtil.isNil(val) || !val.length) {
return metaData
}
const deserializer = metaDataCfg[key].deserialize
if (deserializer && val) {
val = deserializer(val)
}
metaData[key] = val
return metaData
}, {})
return data
}
I need to mock the time for my CodeceptJS tests.
My React component uses the new Date() function:
const Component = () => {
console.log(new Date())
return <h1>Im a component</h1>
}
I need the component to think it's 2018. For my Jest unit tests this was straightforward:
import MockDate from 'mockdate';
MockDate.set('2018-10');
test("test something", ()=>{
// Actual test here
})
MockDate.reset();
How can I do the same with CodeceptJS? Ive tried using the date mocking module in the test:
Scenario('#test', async (CheckoutPage) => {
const MockDate = require('mockdate');
MockDate.set('2018-10');
// Actual test here
});
I also tried dependancy injection. The code within FIX-DATE monkey patches the date:
Scenario(
'#test',
(CheckoutPage, FixDate) => {
FixDate();
CheckoutPage.load();
pause();
}
).injectDependencies({ FixDate: require('./FIX-DATE') });
Neither of these have any affect on the date.
The issue is that CodeceptJS is running inside the browser, so you need to override date object of the browser.
Basically you need to override the Date Object of the browser, or the function that is used, for Example:
// create a date object for this Friday:
var d = new Date(2018, 0, 20);
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d;};
var now = new Date()
console.log(now);
Date.now = function () { return d};
console.log(Date.now());
This is the way to do that in pure JS, the second step is to integrate into codeceptjs, and this can be done using I.executeScript
for Example:
I.executeScript(function () {
var d = new Date(2018, 0, 20);
Date = function(){return d;};
})
You can also create a custom step, for example, I.fakeDate(new Date(2018, 0, 20))
module.exports = function() {
return actor({
fakeDate: function(date) {
I.executeScript(function (fakeDate) {
var d = fakeDate;
window.__original_date = Date;
Date = function(){return d;};
}, date);
},
fakeDateRestore: function() {
I.executeScript(function () {
Date = window.__original_date;
});
}
});
}
Then you just Fake the date when you need, and restore it.
I.Click('beofre');
I.fakeDate(new Date(2018,10,01));
// The test code here
I.fakeDateRestore();
Hope this helps #:-)
I want to call service only when user input is not empty and ith some delay so user finish the typing.
Below is the code. Please help.
Component.ts
searchByName(event) {
this.facilityService.searchFacilityName(event.target.value).subscribe(facilities => this.facilities = facilities);
}
Service.ts
searchFacilityName(name) {
return this.http.get('http://localhost:8000/searchFacilityByName/' + name)
.map((response:Response) => response.json())
.catch(
(error: Response) => {
return Observable.throw('Something went wrong. Please try again.')
}
);
}
This will be helpful,
this.testForm.controls.searchText.valueChanges.subscribe(x=>{
if(this.testForm.controls.searchText.dirty && this.testForm.controls.searchText.valid) {
setTimeout(function(){
this.searchFacilityName(this.testForm.controls.searchText.value)
},3000);
} });
You need to specify a time limit first i.e. amount of time you want to wait after the last keyup event to make sure that the user has stopped typing.
After that you can try this
<input type='text' [ngModel]='userInput' (keyup)='checkTimeLimit()' (keydown)='typeCheck = typeCheck + 1'>
In your component:
typeCheck = 0;
userInput;
timeLimit = 5000; // It is the time limit after which you consider that user has stopped typing (5s)
checkTimeLimit() {
const temp = this.typeCheck;
setTimeout(() => {
if (temp === this.typeCheck) { // It checks whether the user has pressed another key before the specified time limit
this.typeCheck = 0;
this.searchFacilityName(userInput);
}
}, this.timeLimit);
}
I am using UI-grid, and I have a bunch of JS date objects like so:
"dob": new Date('1942-11-19')
I want to be able to filter the column by date when you click the "sort ascending/descending" buttons. As such, I have set the colDef up like so:
{
field: 'dob'
, displayName: 'D.O.B.'
, width: '130'
, editableCellTemplate: '<div><form name="inputForm"><input type="INPUT_TYPE" ng-class="\'colt\' + col.uid" ui-grid-editor ng-model="MODEL_COL_FIELD" style="border-bottom-color: #74B3CE; border-bottom-width: 2px;"></form></div>'
, headerCellClass: $scope.highlightFilteredHeader
, cellTemplate: '<div class="ui-grid-cell-contents" >{{grid.getCellValue(row, col)| date:\'MM-dd-yyyy\'}}</div>'
, cellFilter: 'date'
, type: 'date'
},
however, the column simply does not sort correctly. I even tried to set up a function to sort it from an external button like so:
function mostRecent(){
console.log('clicked mostRecent');
$scope.gridApi.grid.sortColumn(
$scope.gridApi.grid.getColumn('dob'), uiGridConstants.DESC
);
$scope.gridApi.grid.notifyDataChange(uiGridConstants.dataChange.ALL); //this line updates the rest of the columns accordingly
};
But it also causes a mish-mush sort that is not correct. Does anyone know what the issue is? I thought it might have to do with my cellTemplate, but after removing the template, there wasn't a difference...
Yes you are right, ui-grid doesn't support sorting of Date type columns.
However you can define a sortingAlgorithm in the columnDef.
Here is how your column definition should look like:
...
columnDefinition.sortingAlgorithm = function (firstDateString, secondDateString) {
var dateFormat = 'YYYY-MM-DD';
return function (firstDateString, secondDateString, dateFormat) {
if (!firstDateString && !secondDateString) {
return 0;
}
if (!firstDateString) {
return 1;
}
if (!secondDateString) {
return -1;
}
var firstDate = $window.moment(firstDateString, dateFormat);
if (!firstDate.isValid()) {
throw new Error('Invalid date: ', firstDateString);
}
var secondDate = $window.moment(secondDateString, dateFormat);
if (!firstDate.isValid()) {
throw new Error('Invalid date: ', secondDateString);
}
if (firstDate.isSame(secondDate)) {
return 0;
} else {
return firstDate.isBefore(secondDate) ? -1 : 1;
}
};
};
...
Please note that in this example Moment.js is used. It is a very useful library so you might probably find also another place in your project where to use it.
$scope.gridOptions = {
data: 'gridData',
columnDefs: [
{field: 'name', displayName: 'Name'},
{field:'age',
displayName:'Birth Date',
sortFn: function (aDate, bDate) {
var a=new Date(aDate);
var b=new Date(bDate);
if (a < b) {
return -1;
}
else if (a > b) {
return 1;
}
else {
return 0;
}
}
}]
};
Try this
http://plnkr.co/edit/0VD3X5YvuNSWAZlig95X?p=info
reference :
https://github.com/angular-ui/ui-grid/issues/222
You can define the Sorting Algorithm for the date fields in UI Grid like below
columnDefs: [
{
field: 'DateFrom', displayName: 'From',
sortingAlgorithm: function (aDate, bDate, rowA, rowB, direction) {
var a = new Date(moment(aDate, "DD-MM-YYYY").format("YYYY-MM-DD"));
//here DD-MM-YYYY is the current format in which the dates are returned
var b = new Date(moment(bDate, "DD-MM-YYYY").format("YYYY-MM-DD"));
if (a < b) {
return -1;
}
else if (a > b) {
return 1;
}
else {
return 0;
}
}
}
]
We can sort the ui-grid column containing date field in a simplest way.
Make use of cellTemplate in this way:
{
name: "Date",
field: 'date',
cellTemplate:'<div>{{row.entity.date | date:"dd/MM/yyyy"}}</div>'
},
So, you can choose any format for date, for eg. date:"dd-MM" etc.