im new in react native, in this project i want to use picker for sending data to debugger with this code:
note: form & form.TandaPengenal from reducer that i made
const Register = ({navigation}) => {
const {form} = useSelector((state) => state.RegisterReducer);
const dispacth = useDispatch();
const [selectedValue, setSelectedValue] = useState("java");
const onInputChange = (value, inputType) => {
dispacth(setForm(inputType, value));
};
const sendData = () => {
console.log('data yang di kirim: ', form);
};
return (
<View style={styles.picker}>
<Picker
selectedValue={selectedValue}
value={form.tandaPengenal}
style={{height: 28, width: 330}}
onValueChange={(value) => onInputChange(value, 'tandaPengenal'),(itemValue, itemIndex) => setSelectedValue(itemValue)}>
<Picker.Item label="Kartu Pelajar" value="Kartu Pelajar" />
<Picker.Item label="Kitas" value="Kitas" />
<Picker.Item label="KTP" value="KTP" />
<Picker.Item label="NPWP" value="NPWP" />
<Picker.Item label="Passport" value="Passport" />
<Picker.Item label="SIM" value="SIM" />
<Picker.Item label="SIUP" value="SIUP" />
</Picker>
</View>
<Button title="Daftar" onPress={sendData} />
);
};
from this code i cant get the value from picker that i pick, But when i use this code:
const Register = ({navigation}) => {
const {form} = useSelector((state) => state.RegisterReducer);
const dispacth = useDispatch();
const onInputChange = (value, inputType) => {
dispacth(setForm(inputType, value));
};
const sendData = () => {
console.log('data yang di kirim: ', form);
};
return (
<View style={styles.picker}>
<Picker
selectedValue={selectedValue}
value={form.tandaPengenal}
style={{height: 28, width: 330}}
onValueChange={(value) => onInputChange(value, 'tandaPengenal')}>
<Picker.Item label="Kartu Pelajar" value="Kartu Pelajar" />
<Picker.Item label="Kitas" value="Kitas" />
<Picker.Item label="KTP" value="KTP" />
<Picker.Item label="NPWP" value="NPWP" />
<Picker.Item label="Passport" value="Passport" />
<Picker.Item label="SIM" value="SIM" />
<Picker.Item label="SIUP" value="SIUP" />
</Picker>
</View>
<Button title="Daftar" onPress={sendData} />
);
};
i can get the data but the picker only show 1 value.
how can i get the value from picker to debugger and it show all picker value?
Related
I have an issue to solve, last days I was trying to update my DB in Firestore but unfortunately, I can't, I read the documentation and I read another from StackOverflow questions, but don't make my update function, don't know what I make wrong, bellow is my code.
here is my button who send to edit screen he is located in home Screen where I have a list of my information he is inside a map
<IconButton
icon={<Icon as={AntDesign} name="edit" color="success.900" />}
borderRadius="full"
onPress={() =>
navigation.navigate("EditScreen", { userId: user.id }) //here i passing a user id to
editing
}
/>
here is code of my EditScreen
export const EditScreen = ({ navigation }) => {
const [name, setName] = useState("");
const [cep, setCep] = useState("");
const [logradouro, setLogradouro] = useState("");
const [numero, setNumero] = useState("");
const [bairro, setBairro] = useState("");
const [uf, setUf] = useState("");
const usersCollectionRef = collection(db, "users");
const handleChangeName = (value) => setName(value);
const handleChangeCep = (number) => setCep(number);
const handleChangeLogradouro = (value) => setLogradouro(value);
const handleChangeNumero = (number) => setNumero(number);
const handleChangeBairro = (value) => setBairro(value);
const handleChangeUf = (value) => setUf(value);
const updateUser = async (id) => {
const userDoc = doc(usersCollectionRef, id);
const newFields = {
name: handleChangeName,
cep: handleChangeCep,
logradouro: handleChangeLogradouro,
numero: setNuhandleChangeNumeromero,
bairro: handleChangeBairro,
uf: handleChangeUf,
};
await updateDoc(userDoc, newFields);
navigation.navigate("HomeScreen");
};
return (
<SafeAreaView style={{ backgroundColor: "#D4D4D8" }}>
<Center h="100%" bg="dark.600">
<Box ml="-300px" mb="80px" flexDirection="row" alignItems='center'>
<IconButton
size="lg"
icon={<Icon as={AntDesign} name="left" color="orange.600" />}
borderRadius="full"
onPress={() => navigation.navigate("HomeScreen")}
/>
</Box>
<Box mb="25px" w="360px">
<FormControl.Label ml="12px">
<Text bold>Nome</Text>
</FormControl.Label>
<TextInput value={name} onChangeText={handleChangeName} />
</Box>
<Box w="360px">
<FormControl.Label ml="12px">
<Text bold>CEP</Text>
</FormControl.Label>
<TextInput value={cep} onChangeText={handleChangeCep} />
</Box>
<Text fontSize="12px">
busque automaticamente seu edereço atraves do cep
</Text>
<Box flexDirection="row" mt="47px">
<Box w="208px" mr="34px">
<FormControl.Label ml="12px">
<Text bold>Logradouro</Text>
</FormControl.Label>
<TextInput
value={logradouro}
onChangeText={handleChangeLogradouro}
/>
</Box>
<Box w="109px">
<FormControl.Label ml="12px">
<Text bold>Número</Text>
</FormControl.Label>
<TextInput value={numero} onChangeText={handleChangeNumero} />
</Box>
</Box>
<Box flexDirection="row" mt="16px">
<Box w="208px" mr="34px">
<FormControl.Label ml="12px">
<Text bold>Bairro</Text>
</FormControl.Label>
<TextInput value={bairro} onChangeText={handleChangeBairro} />
</Box>
<Box w="109px">
<FormControl.Label ml="12px">
<Text bold>UF</Text>
</FormControl.Label>
<TextInput value={uf} onChangeText={handleChangeUf} />
</Box>
</Box>
<Box mt="50px">
<PrimaryButton onPress={updateUser}>salvar</PrimaryButton>
</Box>
</Center>
</SafeAreaView>
);
};
I'm unaware of the exact issue in this case. However, you do not include where any firebase is updated, only JS for the updating data from the user's perspective. My best advice is to follow the data you care about through console.log() and check whether the data is making to each endpoint.
Best of luck.
Update your updateUser fuction. I think it will work
const updateUser = async (id) => {
const newFields = {
name,
cep,
logradouro,
numero,
bairro,
uf,
};
firestore()
.collection('users')
.doc(id)
.update(newFields)
.then(() => navigation.navigate("HomeScreen"));
.catch(error => console.error('firestore Error', error));
};
How to hide the lists of cities when the textfield is empty and when the user start typing the lists will show.
https://codesandbox.io/s/loving-platform-t2cyb?file=/src/LocationWidget.js
const openSearch = () => {
setViewLocationList(true);
startSearch();
};
const stopSearch = () => {
setSearchParameter('')
setViewLocationList(false);
};
<TextField
variant="outlined"
placeholder="Search Locations"
onFocus={openSearch}
onChange={filterResults}
value={searchParameter}
classes={{notchedOutline:classes.input}}
InputProps={{
endAdornment: (
<IconButton onClick={stopSearch} edge="end">
<ClearIcon />
</IconButton>
),
classes:{notchedOutline:classes.noBorder},
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
/>
</Box>
<Collapse in={viewLocationList} sx={{ my: '2px' }}>
<Box className="rounded-scrollbar widget-result-container">
{filteredLocations.map((location, index) => (
<LocationWidgetItem
key={index}
location={location}
onClickLocation={setActiveLocation}
/>
))}
</Box>
</Collapse>
You have to take state variable in which you have to store whatever user is typing:
const [text,setText] = useState("");
and in your filterLocations you have to update its value
const filterLocations = (txt) => {
setText(txt.target.value);
let filteredLocations = locations.filter((e) =>
e.name.toLowerCase().includes(txt.target.value.toLowerCase())
);
setSearchParameter(filteredLocations);
};
And Finally in your render, render ul conditioanlly
{ !!text && <ul>
{searchParameter.map((location) => (
<li key={location.name}>{location.name}</li>
))}
</ul>}
https://codesandbox.io/s/dreamy-roentgen-0jnoi?file=/src/LocationWidget.js
please find below code.
export default function LocationWidget({ locations }) {
const [searchParameter, setSearchParameter] = useState(locations);
const [inputText, setInputText] = useState(null);
const filterLocations = (txt) => {
setInputText(txt.target.value);
let filteredLocations = locations.filter((e) =>
e.name.toLowerCase().includes(txt.target.value.toLowerCase())
);
setSearchParameter(filteredLocations);
};
return (
<>
<input type="text" onChange={filterLocations} />
{inputText && <ul>
{searchParameter.map((location) => (
<li key={location.name}>{location.name}</li>
))}
</ul>}
</>
);
}
You'd like to set an 'input' eventListener on the input field. And check if the inputField length > 0, then set the setViewLocationList(true); and if the inputField length === 0, then set the setViewLocationList(false).
I'm new to react-native, I'm trying to use Picker item to selct from a dropdown, I'm using react hooks to set Picker items to be selectable, however Expo stops without warning when I add the code:
const HomeScreen3 = observer(() =>
{
const [ options, setOptions ] = useState([ { id:1, title:'Titulo 1' }, { id:2, title:'Titulo 2' } ]);
const [ selectedOption, setSelectedOption ] = useState({ id:1, title:'Titulo 1' });
useEffect(() => {
console.log('component mounted');
}, []);
return (
<View style={{flex: 1, backgroundColor: '#fff', padding:10, position:'relative' }}>
<ScrollView showsHorizontalScrollIndicator={false}>
<Picker
itemStyle={{ backgroundColor: "white", color: "black", borderColor:'rgba(0,0,0,0.2)', fontSize:16, }}
mode="dropdown"
selectedValue={selectedOption}
onValueChange={(value) => { setSelectedOption( value)}}>
{options.map((item, index) => {
return (<Picker.Item label={item} value={item} key={index}/>)
})}
</Picker>
</ScrollView>
</View>
export default HomeScreen3;
for expo use this works for me even is there a warn but works!
import { Picker } from 'react-native'
// state
const [picked, setPicked] = useState(1.15);
<Picker
selectedValue={picked}
style={{ height: 50, width: 100 }}
onValueChange={(itemValue, itemIndex) =>
setPicked(itemValue)
}>
<Picker.Item label="Canda 5%" value={1.05} />
<Picker.Item label="Japan 8%" value={1.08} />
<Picker.Item label="USA 10%" value={1.10} />
<Picker.Item label="Egypt 14%" value={1.14} />
<Picker.Item label="Saudi Arabia 15%" value={1.15} />
<Picker.Item label="China 16%" value={1.16} />
<Picker.Item label="Algeria 17%" value={1.17} />
<Picker.Item label="18%" value={1.18} />
<Picker.Item label="German 19%" value={1.19} />
<Picker.Item label="German 19%" value={1.20} />
</Picker>
First of all, in Expo SDK 38 the import { Picker } from 'react-native'; is no longer working as expected.
Make sure you use import { Picker } from '#react-native-community/picker';
Here is the documentation for it: https://github.com/react-native-community/react-native-picker.
Second, the real problem I see is an issue with your code is that for the Picker.Item, here:
{options.map((item, index) => {
return (<Picker.Item label={item} value={item} key={index}/>)
})}
you are sending the complete objects in the label and item props. However, looking at the actual documentation, label accepts a string and value accepts string or integer - https://reactnative.dev/docs/picker-item
That means your Picker code should look like this:
<Picker
itemStyle={{backgroundColor: "white", color: "black", borderColor:'rgba(0,0,0,0.2)', fontSize:16}}
mode="dropdown"
selectedValue={selectedOption}
onValueChange={(value) => {setSelectedOption(value)}}>
{options.map((item, index) => {
return (<Picker.Item label={item.id} value={item.title} key={index}/>)
})}
</Picker>
and the selectedOption should only store the id of the item like this:
const [ selectedOption, setSelectedOption ] = useState(1);
my constructor has:
this.ActiveDelegation = {
cityArr: [],
name: '',
expiration: '',
}
this is how i get the data from firestore into the object and i assume it add the name inside the cittyArr[] i've created
getDelegationList = (querySnapshot) => {
console.log("snapshot")
querySnapshot.forEach((res) => {
const {name, expiration} = res.data();
console.log('res is =>', res.data())
this.ActiveDelegation.cityArr.push({
key: res.id,
res,
name,
expiration,
});
//return <Picker.Item value={name} label={name} />
});
console.log('test2: ', this.ActiveDelegation.cityArr)
//console.log('test12312: ',this.ActiveDelegation.cityArr.city)
delegList = () => {
return (this.ActiveDelegation.cityArr.map((c, i) => {
return (
<Picker.Item label = {c.name} value = {c.name} key = {i}/>
)
}
))
}
}
this is inside render:
<Item picker>
<Picker
mode="dropdown"
style={{ width: 20 }}
placeholder="choose destination"
placeholderStyle={{ color: "#bfc6ea" }}
placeholderIconColor="#007aff"
// selectedValue={this.state.Destination}
// onValueChange={this.onValueChangeG.bind(this)}
selectedValue={this.state.selectedDest}
onValueChange={ (value) => ( this.setState({selectedDest: value}) ) } >
{this.delegList}
{/*{cityItems}*/}
<Picker.Item label="select" value="" />
</Picker>
</Item>
but nothing happen inside my picker..
can anyone help?
i found a solution. just used the map inside the render itself under the picker scope:
<Item picker>
<Picker
mode="dropdown"
style={{ width: 20 }}
placeholder="choose destination"
placeholderStyle={{ color: "#bfc6ea" }}
placeholderIconColor="#007aff"
selectedValue={this.state.Destination}
onValueChange={ (value) => ( this.setState({Destination: value}) ) } >
{/* onValueChange={this.onValueChangeG.bind(this)} >*/}
{/*<Picker.Item label="choose" value="" />*/}
{
this.state.destinationArr.map( (city, i) => {
return (
<Picker.Item label={city.name} value={city.name} key={i} />
)
})
}
</Picker>
</Item>
fixed*
hi im having troubles with my picker, i need to print a list of options inside my picker but im not able to make it work using hooks, im having troubles with the map function
this is my code
const [vZipCode, setvZipCode] = useState('');
const [vState, setvState] = useState('Estado');
const [vCity, setvCity] = useState('Ciudad');
const [vSuburb, setvSuburb] = useState('Colonia');
const getAddres = ({vZipCode}) => {
axios.post(`http://exitusdesarrollo.eastus2.cloudapp.azure.com/AppForceControllers/controllers/GetAddressController.php`, {vZipCode})
.then(res => {
console.log(res.data.state);
console.log(res.data.city);
console.log(res.data.suburbs);
setvState(res.data.state);
setvCity(res.data.city);
setvSuburb(res.data.suburbs);
})
}
return (
<View>
<TouchableOpacity
style={ styles.logout}
onPress={() => getAddres({vZipCode})}>
<Text style={styles.loginText}>Obtener Ubicacion</Text>
</TouchableOpacity>
<View style={styles.ocointainer}>
<View style={styles.pickcontainer}>
<Picker style={styles.pick}
selectedValue={vSuburb}
onValueChange={newvSuburb => setvSuburb(newvSuburb.toUpperCase())}
>
{setvSuburb.map((item,index)=> {
return <Picker.Item
key={index}
label = {'${item.name}'}
value = {'${item.name}'} />
}
)
}
</Picker>
<TouchableOpacity style={styles.inputIcon} >
<Image source={require('../assets/Flecha.png')}/>
</TouchableOpacity>
</View>
</View>
</View>
this is the array that setvSuburb has
suburbs":[{"0":"Burócrata"},{"1":"El Cielo"},{"2":"Privada de Cortez Residencial"},{"3":"La Aurora"},{"4":"Loma Linda"},{"5":"Aeropuerto"},{"6":"Campo de Tiro"}]
any help would be appreciated
setvSuburb isn't an array. It's a function.
You are mapping over your function, not your data.
You should be using parentheses around your <Picker.item>.
You initialize vSuburb to a string. It should be an empty array.
See if this helps:
{vSuburb.map((item,index) => {
return (
<Picker.Item
key={index}
label = {'${item.name}'}
value = {'${item.name}'}
/>
);
}
Also this:
const [vSuburb, setvSuburb] = useState([]);
You need to return the <Picker.Item />.
let say we have this array:
const suburbs = [
{
"0": 'Burócrata'
},
{
"1": 'El Cielo'
},
{
"2": 'Privada'
},
];
we print a list by using map:
<Picker style={styles.pick}
selectedValue={vSuburb}
onValueChange={newvSuburb => setvSuburb(newvSuburb.toUpperCase())}
>
{suburbs.map((item,index)=> {
return <Picker.Item
key={index}
label = {'${item[index]}'}
value = {'${item[index]}'} />
}
)
}
I hope this will help you