React Native how to set the time and date as the local device? - react-native

I was trying to get the time and date and set as the local device format .
I have tried this api "https://www.npmjs.com/package/react-native-device-time-format?activeTab=readme",
But dosen't work at all ..
Here is my code ,could you please take a look ?
Thank you so much ?
import React,{useEffect,useState} from 'react';
import { StyleSheet, View } from 'react-native';
import { is24HourFormat } from 'react-native-device-time-format';
import moment from 'moment';
function TryTime(props) {
const [currentTime, setCurrentTime] = useState("");
const getCurrentHourFormat = async (date) => {
const is24Hour = await is24HourFormat();
return moment(date).format(is24Hour ? 'HH:mm' : 'h:mm A');
}
useEffect(() => {
(async () => {
const timeNow = await TryTime(Date.now);
setCurrentTime(getCurrentHourFormat(timeNow));
})();
}, []);
return (
<View style={styles.container}>
<Text>{currentTime}</Text>
</View>
);
}
const styles = StyleSheet.create({
container : {
flex : 1,
justifyContent : 'center',
alignItems : 'center',
}
})
export default TryTime;

First, to get the local time of device by JS, you can use a built-in function of js: toLocaleString()
Note:
For this question: Do you know how to get more simple ? Something like 1 sec ago ,10 min ago ,1 hour ago
=> i guess you have the previous date time, and you want to compare it to current time
something like:
a = ... // your previous time
b = new Date().toLocaleString()
Just take let c = b - a as the difference between 2 date, then
c / 1000 => get seconds
c / 1000 * 60 => get minutes
c / 1000 * 3600 => get hours

Related

How to update the style after useState update - React Native

I am currently facing a problem that does bother me a lot.
I am using the react-native-calendar-strip library. I would like to have the ability to deselect a date (update the day container from an orange container to a fully transparent one) which is not natively supported.
So I implemented the code bellow which does not work :
import CalendarStrip from "react-native-calendar-strip";
const EventCalendar = (props) => {
const [selectedDate, setSelectedDate] = useState("");
const [deselectDate, setDeselectDate] = useState(false);
const handleDaySelection = (date) => {
date = date.toLocaleString("fr-FR", option);
if (date == selectedDate) {
setSelectedDate("");
setDeselectDate(true);
} else {
setSelectedDate(date);
setDeselectDate(false);
}
}
return (
<View>
<CalendarStrip
onDateSelected={handleDaySelection}
daySelectionAnimation={{
type: "background",
duration: 200,
highlightColor: deselectDate ?
"rgba(0, 0, 0, 0)" : "#fca051",
}}
/>
In fact, the useState does not have the time to update before the daySelectionAnimation prop is called.
After having tried different things, I actually do not have anymore any ideas that could handle this problem.
Do you have any suggestions to help me handle this problem ?
Thanks guys !

Reset the initial state value in Recat Native

Requirement: I have to blink a View for 2 sec with 2 different color (for ex red and white).
I can do this by using this code -
const [state, setState] = React.useState(false)
const [initialState, setInitialState] = React.useState(0)
React.useEffect(() => {
if (initialState < 2){
let interval = setInterval(() => {
setState(true)
setInitialState(initialState + 1)
setTimeout(() => {
setState(false)
}, 80);
}, 300);
setTimeout(() => {
clearInterval(interval)
}, 600);
}
}, [initialState])
and called it like -
<View style={{...styles.mainContainer, backgroundColor: state ? Colors.GRO7 : Colors.GRC9}}>
Another Requirement: I have another screen from it i an change the address, on successful address change i have to blink this view again for 2 sec. I'm not sure where i can reset the initial value to 0 again.
I am new In react native, could some one guide me how to achieve this functionality
Can‘t completely understand what‘s your target.
Here is a blinking text sample
you can pass in the initial value to this component instead of defining 0 in this line:
const [initialState, setInitialState] = React.useState(0)
you could have a param to pass in and put it instead of 0 so that every time that param changes this component will re render. and so you get a new initial state.
for example:
const [initialState, setInitialState] = React.useState(initialValue)

Suggestion for fetch the data in database and set progress bar

I have already stored the student id and number of books read in the database. now, I have implemented the method to get the details of books count read by the students. but the function progressbardata() doesn't return the data fetched from query. I have tried to assign a value manually inside the db.transaction() and returned it but no luck.
Could you please let me know where i am doing wrong. also this method looping multiple times. how can we sort this out.
import * as Progress from 'react-native-progress';
import { openDatabase } from 'react-native-sqlite-storage';
var db = openDatabase({ name: 'UserDatabase.db' });
let progressbardata = (id) => {
var totalItems=0;
db.transaction((tx) => {
tx.executeSql('SELECT * FROM student where id = ?', [id], (tx, results) => {
totalItems = results.rows.item(0).percent;
return (totalItems);
})
})
}
const _renderContent = (item, index) => {
return (
<View>
<Progress.Bar color='#68FF33' progress={progressbardata(item.id)}/>
</View>
)
}
My guess would be that the request to fetch the data is asynchronous and this code does not seem to wait for a response to continue. Therefor the code would continue while the fetch requests has not returned a value yet. If this is the case, I would suggest that you let the request set the State of the component, and make the state the input of the Progress.Bar component. This way, when the fetch requests finishes asynchronously, the state will be set and the progress bar will be updated. This would look something like this:
import * as Progress from 'react-native-progress';
import { openDatabase } from 'react-native-sqlite-storage';
import { useState } from 'react'
var db = openDatabase({ name: 'UserDatabase.db' });
const renderContent = (props) => {
[progress, setProgress] = useState(0)
let progressbardata = (id) => {
var totalItems=0;
db.transaction((tx) => {
tx.executeSql('SELECT * FROM student where id = ?', [id], (tx, results) => {
totalItems = results.rows.item(0).percent;
setProgress(totalItems);
})
})
}
progressbardata(props.id)
return (
<View>
<Progress.Bar color='#68FF33' progress={progress}/>
</View>
)
}

How to do jest testing in react native?

I have a simple code which I have written to test.
This is my App.js:
const App: () => React$Node = () => {
function sum(a, b) {
alert(a + b);
return a + b;
}
return (
<>
<Button
title="Sum"
onPress={() => {sum(1,2)}}
/>
);
This is my App-test.js in the __tests__ folder:
import 'react-native';
const sum = require('../App');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
When I run npm test I get this error TypeError: sum is not a function. Can anyone help.
Note: When I run it on my android phone it works properly and shows 3 in the alert box.
It's because you are importing sum from your App file but it is not an exported method the way you wrote it.
You can do something like this:
export const sum = (a, b) => {
alert(a + b);
return a + b;
}
export const App = () => (
<Button
title="Sum"
onPress={() => {sum(1,2)}}
/>
);
And use it like this in your test file:
import { sum } from '../App'
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
It's not particularly linked to React Native since you're only trying to test a specific method, which can be use with any framework.

Week Picker In Reactjs and display week like a table with seven days and dates

Use Reactjs and it needs prev and next buttons.
By clicking on the prev button it should go previous week
By clicking on the next button it should go next week
I'm new to Reactjs and I request please anyone helps me out
example
< date-month-year to date-month-year > of a week
Date math is complicated. You can go with something like Moment or Luxon for handling this sort of thing. I like date-fns because it abstracts dealing with the native JS Date object, handling all the basics. Here's an example in a React hook.
// useNextPrevToday
import { useState } from 'react';
import add from 'date-fns/add';
import sub from 'date-fns/sub';
const PERIODS = ['year', 'month', 'week', 'day', 'hour', 'minute'];
export default function () {
const [now, setNow] = useState(DateTime.local());
const checkPeriod = function (period) {
if (!PERIODS.includes(period)) {
throw new Error(`The period ${period} is not valid. Use 'year', 'month', 'week', 'day', 'hour' or 'minute'.`);
}
};
const next = function (period = 'day') {
checkPeriod(period);
setNow((prev) => add(prev, { [`${period}s`]: 1 }));
};
const previous = function (period = 'day') {
checkPeriod(period);
setNow((prev) => sub(prev, { [`${period}s`]: 1 }));
};
const today = function () {
setNow(new Date());
};
return {
next,
previous,
today,
now,
};
}
Then use it
// DateDisplay
import React from 'react';
import useNextPreviousToday from './useNextPreviousToday'
export const DateDisplay = function () {
const [next, previous, today, now] = useNextPreviousToday();
return (
<div>
<button onClick={() => previous('day')}>Previous</button>
<button onClick={() => today()}>Today</button>
<button onClick={() => next('day')}>Next</button>
</div>
<div>
{now.toString()}
</div>
)
};
This is a really rough example, but should point you where you need to go.