get event from main calendar by expo calendar - react-native

I'm trying to use Calendar.getEventsAsync("calendarId", startDate,endDate) to get all events in my calendar from date "startDate" to "endDate". here is part of my code:
export class CalendarScreen extends Component {
...
async getEvents(date){
this.setState({
selectedStartDate: date,
});
console.log("1")
const { status } = await Calendar.requestCalendarPermissionsAsync();
if (status === 'granted') {
try {
console.log("2")
let startDate = new Date(this.state.startDate); //from today
let endDate = this.state.endDate.setDate(startDate.getDate()+1) ;/// to tomorrow
console.log(new Date(startDate))
console.log(new Date(endDate))
const eventi= await Calendar.getEventsAsync('1',new Date(startDate),new Date(endDate));
console.log(eventi)
} catch (error) {
return
}
}
}
render() {
return (
...
<CalendarPicker
onDateChange={this.getEvents}
/>
...
but out put is as bellow:
1
2
2022-07-21T12:11:02.000Z
2022-07-22T12:11:02.514Z
nothing as events

Related

Async function react native

We have to create a Bingo game in React Native with Firebase Realtime Database on Android simulator. The app game is for 2 players. When the first player enter in the app, he create the game and wait for the second player to join.
we want to create a screen with the writing: "Waiting for another player" that appears to the first player until the second player connects then when the second player connects the card is shown.
We wrote this code but it return 'undefined' .
function Game(){
const authCtx = useContext(AuthContext);
const gameCtx = useContext(GameContext);
const [loadPlayer, setLoadPlayer] = useState(false);
useEffect(() => {
async function gamePlay(){
gameCtx.player1 = authCtx.token;
const play = await setGame(authCtx.token, gameCtx);
console.log(play); //return undefined
if(play == 'CREATE'){
setLoadPlayer(true);
}else if(play == 'UPDATE'){
setLoadPlayer(false);
}
if(loadPlayer){
return <LoadingOverlay message="Waiting for another player... " />;
}
}
gamePlay();
}, []);
return <Card />;
}
export default Game;
export function create(game){
const db = getDatabase();
const newGameKey = push(child(ref(db), 'GAME')).key;
set(ref(db, '/GAME/' + newGameKey), game)
.then(() => {console.log('Game Create!');})
.catch((error) => {console.log(error);});
}
export function setGame(email, game){
const dbRef = ref(getDatabase());
var player = false;
get(child(dbRef, 'GAME/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const key1 = snapshot.child(key + '/player1').val();
const key2 = snapshot.child(key + '/player2').val();
if( key2 == "" && email != key1){
console.log('P2');
updateGame(email, key);
player = true;
return true;
}
});
if(player == false){
console.log('P1');
player = true;
create(game);
}
} else {
//create the first game!
create(game);
}
}).catch((error) => {
console.error(error);
});
}
export function updateGame(email, key){
console.log('Update: ' + key);
const db = getDatabase();
const updates = {};
updates['/GAME/' + key + '/player2'] = email;
return update(ref(db), updates);
}
We think this is due to "async" and "await" because not working correctly.
Do you have any suggestions?
How can we redirect the first player to a waiting screen?
is ref(getDatabase()) is promise?. if it is then use await before it.
and use async function before setGame if you are using await while calling.
export async function setGame(email, game){
const dbRef = await ref(getDatabase());
var player = false;
get(child(dbRef, 'GAME/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const key1 = snapshot.child(key + '/player1').val();
const key2 = snapshot.child(key + '/player2').val();
if( key2 == "" && email != key1){
console.log('P2');
updateGame(email, key);
player = true;
return true;
}
});
if(player == false){
console.log('P1');
player = true;
create(game);
}
} else {
//create the first game!
create(game);
}
}).catch((error) => {
console.error(error);
});
}

react native instance class not running in js side

I have this class:
export default class CallManager{
static instance = null
calls = []
static getInstance() {
if (CallManager.instance == null) {
CallManager.instance = new CallManager()
}
return this.instance;
}
addCall(callUUID, data){
this.calls.push({
callId : callUUID,
data: data
})
}
removeCall(callUUID){
this.calls = this.calls.filter(c => c.callId != callUUID)
}
getAllCall(){
return this.calls
}
}
When ios app killed + get incoming call (with RNCallKeep), I'm using this class to store new call like this:
RNCallKeep.addEventListener('didDisplayIncomingCall', ({ error, callUUID, handle, localizedCallerName, hasVideo, fromPushKit, payload }) => {
// you might want to do following things when receiving this event:
// - Start playing ringback if it is an outgoing call
console.log('didDisplayIncomingCall', error, callUUID, handle, localizedCallerName, hasVideo, fromPushKit, payload)
try {
CallManager.getInstance().addCall(callUUID, { ...payload})
} catch (error) {
console.log('didDisplayIncomingCall error', error)
RNCallKeep.endCall(callUUID)
}
})
const answerCall = ({callUUID}) => {
console.log(`[answerCall] ${callUUID}`)
RNCallKeep.answerIncomingCall(callUUID)
const callData = CallManager.getInstance().getAllCall().find(c => c.callId.toString().toUpperCase() === callUUID.toString().toUpperCase())
....
}
But after debug, i got getAllCall return empty. Can someone help?

How can I seperate functions which are basically the same but use different states? Vue2/Vuex

Ive got a problem since i realized that I break the DRY(Dont repeat yourself) rule. So basically I have 2 modules(movies, cinemas) and few methods in them which look the same but use their module' state.
Example: Movies has 'movies' state. Cinemas has 'cinemas' state.
//cinemas.ts
#Mutation
deleteCinemaFromStore(id: string): void {
const cinemaIndex = this.cinemas.findIndex((item) => item.id === id);
if (cinemaIndex >= 0) {
const cinemasCopy = this.cinemas.map((obj) => {
return { ...obj };
});
cinemasCopy.splice(cinemaIndex, 1);
this.cinemas = cinemasCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
//movies.ts
#Mutation
deleteMovieFromStore(id: string): void {
const movieIndex = this.movies.findIndex((item) => item.id === id);
if (movieIndex >= 0) {
const moviesCopy = this.movies.map((obj) => {
return { ...obj };
});
moviesCopy.splice(movieIndex, 1);
this.movies = moviesCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
My struggle is: How can I seperate these methods into utils.ts if they have reference to 2 different states?
define another function that take the id, state and store context (this) as parameters :
function delete(id:string,itemsName:string,self:any){
const itemIndex= self[itemsName].findIndex((item) => item.id === id);
if (itemIndex>= 0) {
const itemsCopy = self[itemsName].map((obj) => {
return { ...obj };
});
itemsCopy.splice(itemIndex, 1);
self[itemsName] = itemsCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
then use it like :
//cities.ts
#Mutation
deleteCityFromStore(id: string): void {
delete(id,'cities',this)
}
//countries.ts
#Mutation
deleteCountryFromStore(id: string): void {
delete(id,'countries',this)
}

inserts an event into the default calendar using the Calendar API

It seems I can't insert an event into the default calendar on my device using react-native and expo sdk. I tried this:
import * as Permissions from 'expo-permissions';
import * as Calendar from 'expo-calendar';
import { Platform } from 'react-native';
...
async obtainDefaultCalendarId() {
let calendar = null;
if (Platform.OS === 'ios') {
calendar = await Calendar.getDefaultCalendarAsync();
} else {
const calendars = await Calendar.getCalendarsAsync();
calendar = calendars
? calendars.find((cal) => cal.isPrimary) || calendars[0]
: null;
}
return calendar ? calendar.id.toString() : null;
}
async obtainCalendarPermission() {
let permission = await Permissions.getAsync(Permissions.CALENDAR);
if (permission.status !== 'granted') {
permission = await Permissions.askAsync(Permissions.CALENDAR);
if (permission.status !== 'granted') {
Alert.alert('Permission not granted to access the calendar');
}
}
return permission;
}
async addReservationToCalendar(date) {
await this.obtainCalendarPermission();
CalendarId = this.obtainDefaultCalendarId();
const startDate = new Date(Date.parse(date));
const endDate = new Date(Date.parse(date) + 2 * 60 * 60 * 1000);
Calendar.createEventAsync(CalendarId, {
title: 'Con Fusion Table Reservation',
location:
'121, Clear Water Bay Road, Clear Water Bay, Kowloon, Hong Kong',
startDate: startDate,
endDate: endDate,
timeZone: 'Asia/Hong_Kong',
});
Alert.alert('Reservation has been added to your calendar');
}
...
It asked for the permission but didn't add an event to my calendar. Before I see any error in my screen the expo client app is crushed.
I didn't get where the error occurs. When I console.log(CalendarId), I got this,
Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
}
I heartily thank if anyone helps me to figure out this.
const newCalendarID = await Calendar.createEventAsync(
calendar.id, {
...
}
);

Subtract 2 times in react-native

I want to subtract two times and check if check_in time > 12Hr then navigate to checkin screen. This is my code snippet
class SplashView extends Component {
componentDidMount() {
const curr_time = moment().format('hh:mm:ss');
const checkin_time = moment(this.props.datetime).format('hh:mm:ss');
// const diff = moment.duration(checkin_time.diff(curr_time));
console.log("TIME&&&&&&&&", curr_time, checkin_time);
setTimeout(() => {
if (this.props.employee_id === null) {
this.props.navigation.navigate('Login');
} else {
this.props.navigation.navigate('Checkin');
}
}, 1000)
}
render() {
return ();
}
}
I'm using moment.js and the value of this.props.datetime is '2019-02-04 14:52:01'. This is my checkin time.
You can get the difference in hours like this:
const diff = moment.duration(checkin_time.diff(curr_time)).as('hours');
Or you can just use moment's diff function
const diff = checkin_time.diff(curr_time, 'hours')
and then compare if (diff > 12) { ... }