Hi how can I use https://momentjs.com/docs/#/i18n/ in react native ? I exactly need to know how to change the language on my calendar.
Now I have name mounths in Polish but name days I have in english but I nedd Polish.
import momentPL from 'moment/src/locale/pl'
function TermeScreen({ route, navigation }) {
const { id, title } = route.params;
const [selectedDate, setSelectedDate] = useState(new Date());
moment.locale('pl',momentPL );
let startDate = moment()
Try this,
import moment from 'moment';
function TermeScreen({ route, navigation }) {
const { id, title } = route.params;
const [selectedDate, setSelectedDate] = useState(new Date());
let startDate = moment(selectedDate.format("YYYY-MM-DD");
}
Related
I tried to build a PWA with next.js
My idea is that i call the API to get data .But sometimes that API does not give the right datatypes or the data are not available.
My project is about showing the canteen nearby and show theirs menu
I checked the API , so i knew that sometime it give back the wrong data for the date.
Could someone to help me to handle it.
Here is my codes :
import {useState} from 'react';
import {useEffect} from 'react';
import {useRouter} from 'next/router';
console.log('test');
const Test = () => {
const current = new Date();
const year = current.getFullYear();
const month = current.getMonth() + 1;
const day = current.getDate();
const today = `${year}-${month<10?`0${month}`:`${month}`}-${day}`;
const [date, setDate] = useState(today);
const [menu, setMenu] = useState([]);
const router = useRouter();
const { id } = router.query;
console.log(id);
console.log(date);
const handleMenu = async () => {
const open = await fetch(`https://openmensa.org/api/v2/canteens/${id}/days/${date}`);
const openData = await open.json();
console.log(openData);
console.log(openData['closed']);
if (openData['closed'] === false) {
const res = await fetch(`https://openmensa.org/api/v2/canteens/${id}/days/${date}/meals`);
const data = await res.json();
console.log(data);
setMenu(data);
}
else {
console.log('closed');
const data = [{id:1,name :'Mensa ist geschlossen'}];
}
}
return (
<div>
<input type="text"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<button onClick={handleMenu}>Get Menu</button>
<h1>Menu</h1>
<p>This is the Menu page</p>
{menu.map((meal) => (
<div key={meal.id}>
<h3>{meal.name}</h3>
<p>Price for students :{meal.prices.students}</p>
<p>Price for employees :{meal.prices.employees}</p>
<p>Price for othters :{meal.prices.others}</p>
<p>Price for pupils :{meal.prices.pupils} kostenlos</p>
</div>))}
</div>
);
}
export default Test;
And here is the error i got
Unhandled Runtime Error
pages/mensen/[id]/review/menu.js (26:40) # eval
24 | const open = await fetch(`https://openmensa.org/api/v2/canteens/${id}/days/${date}`);
25 |
> 26 | const openData = await open.json();
| ^
27 | console.log(openData);
28 | console.log(openData['closed']);
29 |
Thank you so much .
let { eventDate } = this.state;
if (eventDate <= 0) {
this.setState({ isTimerOver: true});
}
Here I need to write this in functional components. can you help me to do this
You can use useState hook in functional component
import { useState } from 'react';
...
const yourFunctionName = () => {
const [ eventDate, setEventDate ] = useState(0) // set initial value here
// The first value eventDate , is our current state.
// The second value setEventDate, is the function that is used to update eventDate state
const [ isTimerOver, setIsTimerOver ] = useState(false) // set initial value
...
if (eventDate <= 0) {
setIsTimerOver(true); // function to update the state isTimerOver
}
...
}
export default yourFunctionName;
Refer this : React useState Hook
I want to create a login page where an error message is displayed when fields are empty. I use function components, state and props to keep the UI separated from the logic. So I have a UserSignInController which returns a UserSignInView which gets displayed on screen.
When I set a onPress callback for the login button, it calls onClickCheckLogin() in the controller. But setting the error message only works if I use an arrow function as a prop, if I use .bind(this) it doesn't.
This works
UserSignInController.js:
import React, {useState} from 'react';
import { Linking, Alert } from 'react-native';
import UserSignInView from './UserSignInView';
import User from '../../User';
const renderSignInView = () =>
{
const [errorMessage, setErrorMessage] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
return (
<UserSignInView
errorMessage = {errorMessage}
setUsername = {setUsername}
setPassword = {setPassword}
//arrow function passing the state to onClickCheckLogin
checkLogin = {() => { onClickCheckLogin(username, password, setErrorMessage)}}
openPrivacyPolicy = {onClickOpenPrivacyPolicy}
/>
)
};
const onClickCheckLogin = (username, password, setMessageFunction) =>
{
if(!! username && !! password)
{
console.log("yeee");
}else
{
console.log('doooo');
setMessageFunction('Username/password empty');
}
};
This does not work UserSignInController.js:
import React, {useState} from 'react';
import { Linking, Alert } from 'react-native';
import UserSignInView from './UserSignInView';
import User from '../../User';
const renderSignInView = () =>
{
const [errorMessage, setErrorMessage] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
//bind function instead of arrow function
onClickCheckLoginCallback = onClickCheckLogin.bind(this);
return (
<UserSignInView
errorMessage = {errorMessage}
setUsername = {setUsername}
setPassword = {setPassword}
//use the binded version
checkLogin = {onClickCheckLoginCallback}
openPrivacyPolicy = {onClickOpenPrivacyPolicy}
/>
)
};
const onClickCheckLogin = () =>
{
if(!! this.username && !! this.password)
{
console.log("yeee");
}else
{
console.log('doooo');
this.setErrorMessage('Username/password empty');
}
};
With this I get an error TypeError: _this.setErrorMessage is not a function. (In '_this.setErrorMessage('Username/password empty')', '_this.setErrorMessage' is undefined)
I found the answer here. You can't access local properties of a function from the outside. That globalObject displayed with console.log is just the window object. So, binding with .bind() can't work. As an alternative, you may pass the setErrorMessage property as an argument, and also the username and password.
I wrote on a separate answer to better distinguish from the first one
I think that the problem is that renderSignInView is defined as an arrow function itself. The this keyword is not pointing to the component then, so calling setErrorMessage results in an error. Try changing to the following:
function renderSignInView(){
//Component
}
I use react hooks,firebase to build a react native app.
I am pretty struggling about using Hooks with FlatList.
I am trying to creating pagination with Firestore. However, I am not sure how to trigger onEndReached using useEffect
It is what I tried:
const [isFetching, setIsFetching] = useState(false)
useEffect(() => {
if(isFetching == false){
_initFirestoreQuery()
}
}, [])
_initFirestoreQuery = async()=>{
const limit = 6
const initialQuery = firebase.firestore().collection('xxxx').orderBy('displayName', 'desc').limit(limit)
const documentSnapshots = await initialQuery.get()
const documentData = documentSnapshots.docs.map(document => document.data());
const lastVisible = documentData[documentData.length - 1].displayName;
setLast(lastVisible)
setData(documentData)
setIsFetching(true)
}
_moreFirestoreQuery = async () =>{
if(isFetching == true){
const limit = 6
const additionalQuery = firebase.firestore().collection('xxxx').orderBy('displayName', 'desc').startAfter(last).limit(limit)
const documentSnapshots = await additionalQuery.get();
const documentData = documentSnapshots.docs.map(document => document.data());
const lastVisible = documentData[documentData.length - 1].displayName;
setLast(lastVisible)
setData(data =>[...data,...documentData])
}
}
<FlatList
onEndReached ={_moreFirestoreQuery}
...
>
Any Idea of doing this if it is impossible how could I do it and is there any alternative for doing this
I am new to react native, and I can successfully run navigate example (https://reactnavigation.org/docs/en/params.html) locally:
But I don't understand, why this code:
const { navigation } = this.props;
const itemId = navigation.getParam('name', 'NO-ID');
can succefully get the value of variable 'name', but if I modified it to:
//const { navigation } = this.props;
const itemId = this.props.getParam('name', 'NO-ID');
Android emulator would complain:
undefined is not a function (evaluating const itemId = this.props.getParam('name', 'NO-ID') )
?
Since { navigation } would be same as this.props ?
you have confused with es6 destructuring.
const { navigation } = this.props;
is equal to
const navigation = this.props.navigation;
It is just a syntactic sugar.
In your case you should correct your code like below:
const itemId = this.props.navigation.getParam('name', 'NO-ID')
You forgot this.props.NAVIGATION :)
// const { navigation } = this.props;
const itemId = this.props.navigation.getParam('name', 'NO-ID');