display selected date from date piker in react native - react-native

I'm trying to use a datepiker in react native to consolelog the piked date when I click on the Button i want to console.log(slected) selected date
const [text, setTextname] = useState();
const [mydate, setDate] = useState(new Date());
const [displaymode, setMode] = useState('date');
const [isDisplayDate, setShow] = useState(false);
const changeSelectedDate = (event, selectedDate) => {
const currentDate = selectedDate || mydate;
let date = moment(selectedDate).format('DD/MM/YYYY');
console.log('dadad', date);
setTextname(date);
setShow(false);
};
const showMode = currentMode => {
setShow(true);
setMode(currentMode);
};
const displayDatepicker = () => {
showMode('date');
};
function getdata() {
console.log('sdsds', text);
}
<Button onPress={displayDatepicker} title="Show date picker!" />
{isDisplayDate && (
<DateTimePicker
testID="dateTimePicker"
value={mydate}
mode={displaymode}
is24Hour={true}
display="default"
onChange={text => changeSelectedDate()}
// onChange={changeSelectedDate}
/>
)}
<View style={styles.buttonw}>
<Button
color="#7743DB"
title="Lets Go"
type="submit"
onPress={() => getdata()}
/>
</View>
i have displayed the datepiker but i am not able to pick a date and pass it to getdata

Remove
const [text, setTextname] = useState();
Replace in function changeSelectedDate
setTextname(date);
with
setDate(date);
and
const currentDate = selectedDate || mydate
by
const currentDate = selectedDate
and lastly
function getdata() {
console.log('sdsds',mydate);
}
changes to function
const changeSelectedDate = (event, selectedDate) => {
setDate(selectedDate);
setShow(false);
};
function getdata() {
let date = moment(mydate).format('DD/MM/YYYY');
console.log('sdsds',date);
}

You have to set date on setDate state in your change date function.
setDate(date);----->add this
setTextname(date);

Related

Why when I enter 1999-10-17 it submits 1999-10-01 React native?

I'm trying to submit a form with a birthdate. But for one or another reason when I for example enter 1999-10-17 it submits 1999-10-01. It just always removes the last number and puts a 0 before. I've been trying everything I could imagine but nothing works...
Why this happens and how can I solve it???
const [birthdate, setBirthdate] = useState('');
const [yearB, setYearB] = useState('');
const [monthB, setMonthB] = useState('');
const [dayB, setDayB] = useState('');
const updateBirthdate = () => {
setBirthdate(`${yearB}-${monthB}-${dayB}`);
};
const handleYearBChange = (yearB) => {
setYearB(yearB);
updateBirthdate();
};
const handleMonthBChange = (monthB) => {
setMonthB(monthB);
updateBirthdate();
};
const handleDayBChange = (dayB) => {
setDayB(dayB);
updateBirthdate();
};
<TextInput
value={yearB}
onChangeText={handleYearBChange}
onSubmitEditing={() => yearBInput.current.blur()}
placeholder="year"
keyboardType="numeric"
/>
<TextInput
value={monthB}
onChangeText={handleMonthBChange}
onSubmitEditing={() => monthBInput.current.blur()}
placeholder="month"
keyboardType="numeric"
/>
<TextInput
value={dayB}
onChangeText={handleDayBChange}
onSubmitEditing={() => dayBInput.current.blur()}
placeholder="day"
keyboardType="numeric"
/>
You must use useEffect hook to update the birthdate with each rendering, follow the example:
const updateBirthdate = useCallback(() => {
setBirthdate(`${yearB}-${monthB}-${dayB}`);
}, [yearB, monthB, dayB]);
const handleYearBChange = (yearB) => {
setYearB(yearB);
};
const handleMonthBChange = (monthB) => {
setMonthB(monthB);
};
const handleDayBChange = (dayB) => {
setDayB(dayB);
};
useEffect(() => {
updateBirthdate()
}, [updateBirthdate])

react-native validation with useState and useCallback

I use useCallback validation for useState value, but that has get value delay.
This is my useState code
const [loading, setLoading] = useState(false);
const [amount, setAmount] = useState('');
const [rate, setRate] = useState('');
const [term, setTerm] = useState('');
const [type, setType] = useState('');
const [title, setTitle] = useState('');
const [canCalc, setCanCalc] = useState(false);
const [bText, setBtext] = useState(styles.defText);
const amountRef = useRef<TextInput | null>(null); //커서 직접이동
const rateRef = useRef<TextInput | null>(null);
const termRef = useRef<TextInput | null>(null);
const typRef = useRef<SelectDropdown | null>(null);
and useState uses inputtext
<TextInput
style={styles.textInput}
onChangeText={(text) =>onchangeAmount(text)}
value={amount}
placeholderTextColor="#666"
importantForAutofill="no"
keyboardType="decimal-pad"
clearButtonMode="while-editing"
returnKeyType="next"
ref={amountRef}
blurOnSubmit={false}
/>
All about useState TextInput same and different value amount, term...
And validation like this:
const onchangeAmount = useCallback(text => {
setAmount(text.trim());
checkValid(amount, rate, term, type,loading);
}, [checkValid]);
const onchangeRate = useCallback(text => {
setRate(text.trim());
checkValid(amount, rate, term, type,loading);
}, [checkValid]);
const onchangeTerm = useCallback(text => {
setTerm( text.trim());
checkValid(amount, rate, term, type);
}, [checkValid]);
const onChangeType = useCallback(text => {
setType(text);
checkValid(amount, rate, term, type,loading);
}, [checkValid]);
function checkValid (amount, rate, term, type,loading){
setLoading(true);
console.log( amount)
console.log( rate)
console.log( term)
console.log( type)
// if (loading) {
// return;
// }
console.log(loading)
//
// const valid=() =>{
// console.log( 'typeof ter========m')
console.log( amount)
console.log( rate)
console.log( term)
// console.log( type.type)
// console.log( type.type !=0)
console.log( !amount )
console.log( !amount && !amount.trim())
//
if (!amount || !amount.trim()) {
return Alert.alert('알림', '이메일을 입력해주세요.');
}
if(
!amount && !amount.trim() &&
!rate && !rate.trim() &&
!term && !term.trim() &&
Object.keys(type).length>0){
console.log("asdfasdfasdfasdf")
setCanCalc(true);
setBtext(styles.actText);
}else{
setCanCalc(false);
setBtext(styles.defText);
}
that validation for change style Pressable grey or blue
<Pressable
onPress={toComplate}
style={canCalc ?
styles.calcActive
:styles.buttonDef
}
disabled={!canCalc}
>
{loading?(
<ActivityIndicator color="white" />
):(
<Text
style={bText}>
calculation
</Text>
)
}
</Pressable>
Why delay get useState value?
Run the validation on an useEffect listening to amount change, that would simplify and make the flow more straight forward. Later on, use the result of the validation to set a different state variable, like the following:
useEffect(() => {
const isValid = runValidations(amount);
setIsValid(isValid)
}, [amount])

How to select one item of the array, when the user selects the contact?

What im trying to do is to select one or more phone numbers from the user contact list.
function ContactList() {
const [checked, setChecked] = useState(false);
const [contacts, setContacts] = useState([]);
const [filter, setFilter] = useState([]);
const [search, setSearch] = useState('');
const [data, setData] = useState(contacts)
useEffect(() => {
(async () => {
const { status } = await Contacts.requestPermissionsAsync();
if (status === 'granted') {
const { data } = await Contacts.getContactsAsync({
fields: [Contacts.Fields.PhoneNumbers],
});
if (data.length > 0) {
setContacts(data);
setFilter(data);
}
}
})();
}, []);
const searchFilter = (text) => {
if (text) {
const newData = contacts.filter((item) => {
const itemData = item.name ? item.name.toUpperCase() : ''.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setFilter(newData);
setSearch(text);
} else {
setFilter(contacts);
setSearch(text);
}
};
const onChangeValue = () => {
setChecked(!checked)
};
useEffect(() => {
checked &&
setData((previous) => [...previous, {phone: contacts}])
}, [checked]
return(
<View>
<CheckBox
style={{ width: 15, height: 15 }}
right={true}
checked={checked}
onPress={onChangeValue}
/>
</View>
);
export default ContactList;
So far, when the user selects one phone number, it will select all phone numbers on his contact list.
I think I should get with the index only one contact from the list but I don't know how to get there.
How can I solve this error?
You can maintain a Map for checkboxes.
const [checked, setChecked] = useState(new Map());
on change use index to set values in Map.
const onChangeValue = (index) => {
checked.set(index, true)
};
in JSX use like this
<CheckBox
style={{ width: 15, height: 15 }}
right={true}
checked={checked.get(index)}
onPress={()=>onChangeValue(index)}
/>

TypeError: date is not a function

const [date, setDate] = useState(new Date(1598051730000));
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const onChange = (event, selectedDate) => {
const currentDate = selectedDate || date;
setShow(Platform.OS === 'ios');
setDate(currentDate);
};
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
showMode('date');
};
<DateTimePicker
testID="dateTimePicker"
display="default"
mode={mode}
value={date}
onChange={(date) => {
setShow(Platform.OS === 'ios');
if (date) {
date(new Date(date));
}
}}
onChangeText={(val) => set_birthdate(val)}
/>
TypeError: date is not a function. (In 'date(new Date(date))', 'date' is an instance of Object)
Can someone help me with this?
i'm adding the full code
I think you should use setDate(new Date(date)) instead of date(new Date(date)); also please rename your arg for avoiding confusion, try below code
onChange={(newDate) => {
setShow(Platform.OS === 'ios');
newDate && setDate(new Date(newDate));
}}

Variable "" has coerced Null value for NonNull type 'String!" GraphQl error

I am trying to save groupChatName as the value of the TextInput and save that name on the backend but in doing so I am getting the error "Possible unhandled promise, data: null, variable 'groupChatName' has coerced Null value for NonNull type 'String'", path: null.
export const createGroupChat = `mutation createGroupChat($groupChatName:String! $messages:String $createdUser:String! $users:String) {
createGroupChat(input:{
groupChatName:$groupChatName
messages:$messages
createdUser:$createdUser
users:$users
}){
groupChatName
messages
createdUser
users
}
}`;
const [currentUser, setCurrentUser] = useState('');
const [value, setValue] = useState('');
const [groupChatName, setGroupChatName] = useState('');
useEffect(() => {
Auth.currentAuthenticatedUser()
.then(currentUser => setCurrentUser(currentUser))
.catch (() => setUsername(null));
}, []);
GroupChat = () => {
if (value.length > 0) {
setValue('')
setGroupChatName('')
props.navigation.navigate('Message', { value });
}
};
GroupChatMutation = async () => {
const GroupChatDetails = { groupChatName, currentUser };
const newGroupChat = await API.graphql(graphqlOperation(createGroupChat, { GroupChatDetails }));
console.log(JSON.stringify(newGroupChat));
};
return (
<View style={styles.container}>
<Text style={styles.header}>Create GroupChat Name</Text>
<View style={styles.textInputContainer}>
<TextInput
style={styles.textInput}
multiline={true}
placeholder={'Type in a GroupChatName'}
placeholderTextColor="#abbabb"
value={value}
onChangeText={value => setValue(value)}
onChange={value => setGroupChatName(value)}
/>
.......```