I am trying to update my full screen on pressing a button. I have tried updating States but is not working for my case. I don't know if its causing for the async function or not.
This is my states:
const [bNumber, setBNumber] = React.useState('');
const [rollNumWeight, setRollNumWeight] = useState([]);
const [rollNumber, setRollNumber] = useState('');
const [rollWeight, setRollWeight] = useState('');
Bellow is function I am using:
const saveRoll = async () => {
try {
const response = await fetch('someURL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
roll_num_weight: rollNumWeight,
bNumber: bNumber
})
});
const json = await response.json();
setBNumber('')
setRollNumber('')
setRollWeight('')
setRollNumWeight([])
AlertButton('Rolls Saved Successfully!')
} catch (error) {
console.error(error);
}
}
I am inputting some data on this stage so my states changes from initial state. Then I am pressing SAVE button
This is the button I am calling my function from:
<TouchableOpacity style={styles.button} onPress={saveRoll}>
<Text style={styles.buttonText}>Save</Text>
</TouchableOpacity>
After Pressing the save button it nothing changes. All the states remain the same.
Bellow is my full render code:
<View style={styles.container}>
<ScrollView
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}>
<View style={styles.app}>
<View style={styles.col1}>
<Text>WORKORDER/BATCHNO</Text>
<SelectDropdown
data={batches}
onSelect={(selectedItem) => {
// getData(selectedItem)
setBNumber(selectedItem)
}}
defaultButtonText={'Select Batch NO'}
buttonTextAfterSelection={(selectedItem, index) => {
return selectedItem;
}}
rowTextForSelection={(item, index) => {
return item;
}}
buttonStyle={styles.input}
buttonTextStyle={styles.dropdown1BtnTxtStyle}
renderDropdownIcon={isOpened => {
return <FontAwesome name={isOpened ? 'chevron-up' : 'chevron-down'} color={'#444'} size={18} />;
}}
dropdownIconPosition={'right'}
dropdownStyle={styles.dropdown1DropdownStyle}
rowStyle={styles.dropdown1RowStyle}
rowTextStyle={styles.dropdown1RowTxtStyle}
selectedRowStyle={styles.dropdown1SelectedRowStyle}
search
searchInputStyle={styles.dropdown1searchInputStyleStyle}
searchPlaceHolder={'Search here'}
searchPlaceHolderColor={'darkgrey'}
renderSearchInputLeftIcon={() => {
return <FontAwesome name={'search'} color={'#444'} size={18} />;
}}
/>
</View>
<View pointerEvents="none">
</View>
<View style={styles.row}>
<View style={styles.col1}>
<Text>Roll Number</Text>
<TextInput
placeholder='Roll Number'
keyboardType='numeric'
style={styles.input}
value={rollNumber}
onChangeText={(val) => setRollNumber(val)} />
</View>
<View style={styles.col1}>
<Text>Roll Weight</Text>
<TextInput
placeholder='Roll Weight'
keyboardType='numeric'
style={styles.input}
value={rollWeight}
onChangeText={(val) => setRollWeight(val)} />
</View>
</View>
<Button title=' Add ' onPress={addRoll}></Button>
</View>
<TouchableOpacity style={styles.button} onPress={saveRoll}>
<Text style={styles.buttonText}>Save</Text>
</TouchableOpacity>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
<Row data={tableHead} style={styles.head} textStyle={styles.text}/>
<Rows data={rollNumWeight} textStyle={styles.text}/>
</Table>
</ScrollView>
</View>
);
Related
I have created a TouchableOpacity which has an icon. The onPress method calls Image Picker.
<View style={styles.container}>
<TouchableOpacity style={styles.buttonStyle} onPress={pickImage}>
<MaterialIcons name="add-to-photos" size={24} color="black" />
</TouchableOpacity>
<TouchableOpacity style={styles.buttonStyle}>
<MaterialIcons name="add-to-photos" size={24} color="black" />
</TouchableOpacity>
</View>
Once the image is picked I am using useState to set the URI value to a variable Image1. Now I am want to display the Selected Image in the TouchableOpacity once the Image is picked.
How can I show selected image and not the icon once the image is picked.
You can do that using useState:
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';
export const Avtar = () => {
const [image, setImage] = useState(null);
const pickImage = () => {
launchImageLibrary(options, async response => {
if (!response.didCancel) {
if (typeof onImageGet === 'function') {
setImage(response.assets[0].uri);
}
}
});
};
return (
<View style={styles.container}>
<TouchableOpacity style={styles.buttonStyle} onPress={pickImage}>
{!!image ? (
<Image
src={source}
style={[{width, height, borderRadius}, avtarStyle]}
resizeMode="cover"
/>
) : (
<MaterialIcons name="add-to-photos" size={24} color="black" />
)}
</TouchableOpacity>
<TouchableOpacity style={styles.buttonStyle}>
{!!image ? (
<Image
src={source}
style={[{width, height, borderRadius}, avtarStyle]}
resizeMode="cover"
/>
) : (
<MaterialIcons name="add-to-photos" size={24} color="black" />
)}
</TouchableOpacity>
</View>
);
};
Try with this:
const [imgPicker, setImgPicker] = useState('');
const cameraOpen = async () => {
const permisoCamara = await ImagePicker.requestCameraPermissionsAsync();
if (permisoCamara.status === "granted") {
const imgCamara = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false,
aspect: [4, 4],
quality: 0.1,
base64: true,
});
if (!imgCamara.cancelled) {
setImgPicker(imgCamara.base64);
}
} else {
alert("Permissions needed");
}
};
return (
<View>
<TouchableOpacity onPress={cameraOpen()}>
{imgPicker == '' ?
<MaterialIcons name="add-to-photos" size={24} color="black" /> :
<Image
source={{
uri: 'data:image/png;base64,' + imgPicker,
}}
/>
}
</TouchableOpacity>
</View>
);
The conditional that you need is inside the Touchable, just validate if the state have any value or not. Hope it helps
I have a screen with card views.
Each card view has:
1x picture
1x title
1x description
1x touchable opacity
I was hoping to figure out a way that each touchable opacity has different navigation.
Item 0 will have navigation to screen x, the item 1 will have navigation to screen y.
My doubt is it possible to have different functions for each touchable opacity ?
function ServiceCoverageButtong() {
const navigation = useNavigation();
return (
<View>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('GeneralInformationSupportScreen')}>
<Text style={styles.buttonText}>Teste</Text>
</TouchableOpacity>
</View>
);
}
const CardItemNewsProvider = ({item, index}) => {
return (
<View style={styles.container} key={index}>
<Image source={item.imgUrl} style={styles.image} />
<Text style={styles.header}>{item.title}</Text>
<Text style={styles.body}>{item.body}</Text>
<ServiceCoverageButtong />
</View>
);
};
How can I create several functions and use the item of CardItemNewsProvider?
I am new to React Native and I am struggling with doing that.
Thanks :)
Yes it's possible. You can pass a prop to your <ServiceCoverageButtong state={"0"}/>
And in your ServiceCoverageButtong() get the state from your props and run a check on what should be returned.
function ServiceCoverageButtong({state}) {
const navigation = useNavigation();
if (state == "0") {
return (
<View>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('GeneralInformationSupportScreen')}>
<Text style={styles.buttonText}>Teste</Text>
</TouchableOpacity>
</View>
);
}
} else {
return (
<View>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('anotherScreen')}>
<Text style={styles.buttonText}>Teste</Text>
</TouchableOpacity>
</View>
);
}
}
If you use one component for your buttons, you can just add onPress prop to your DataNewsProvider
let DataNewsProvider = [
{
title: NewsHomeCountryTitle,
body: NewsHomeCountryBody,
imgUrl: Images.newsYourCountryImage,
textButton: NewsTextButton,
onPress: () => navigation.navigate('GeneralInformationSupportScreen'),
},
{
title: NewsWorldwideTitle,
body: NewsWorldwideBody,
imgUrl: Images.newsWorldwideImage,
textButton: NewsTextButton,
onPress: () => navigation.navigate('anotherScreen'),
},
];
And pass it to your button components TouchableOpacity
const CardItemNewsProvider = ({item, index}) => {
return (
<View style={styles.container} key={index}>
<Image source={item.imgUrl} style={styles.image} />
<Text style={styles.header}>{item.title}</Text>
<Text style={styles.body}>{item.body}</Text>
<ServiceCoverageButtong state={item.stateButton} onPress={item.onPress}/>
</View>
);
};
This way you don't need to have additional conditions, and you just pass those functions as it is.
Thanks caslawter!
For anyone interested.
function ServiceCoverageButtong({state}) {
const navigation = useNavigation();
if (state === '0') {
console.log('state', state);
return (
<View>
<TouchableOpacity
style={styles.button}
onPress={() =>
navigation.navigate('GeneralInformationSupportScreen')
}>
<Text style={styles.buttonText}>Hi I'm a test</Text>
</TouchableOpacity>
</View>
);
} else {
console.log('state', state);
return (
<View>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('anotherScreen')}>
<Text style={styles.buttonText}>You're really into testing</Text>
</TouchableOpacity>
</View>
);
}
}
const CardItemNewsProvider = ({item, index}) => {
return (
<View style={styles.container} key={index}>
<Image source={item.imgUrl} style={styles.image} />
<Text style={styles.header}>{item.title}</Text>
<Text style={styles.body}>{item.body}</Text>
<ServiceCoverageButtong state={item.stateButton} />
</View>
);
};
And another snipet:
let DataNewsProvider = [
{
title: NewsHomeCountryTitle,
body: NewsHomeCountryBody,
imgUrl: Images.newsYourCountryImage,
textButton: NewsTextButton,
stateButton: '0',
},
{
title: NewsWorldwideTitle,
body: NewsWorldwideBody,
imgUrl: Images.newsWorldwideImage,
textButton: NewsTextButton,
stateButton: '1',
},
];
I am implementing my own Modal, trying to replace the Alert.alert with something more beautiful. I made it to be displayed when needed, but it is not hiding on the button press, but I think I transferred it the needed function. My modal structure is the following:
export const RCModal = ({ title, visible, onButtonPress }) => {
return (
<Modal
animationType='fade'
transparent={true}
visible={visible}
>
<View style={styles.container}>
<Text style={styles.title}>{title}</Text>
<Pressable style={styles.button} onPress={onButtonPress}>
<Text style={styles.text}>OK</Text>
</Pressable>
</View>
</Modal>
)
};
And it is used in the application in the following way:
// ...
const [alertVisible, setAlertVisible] = useState(false);
const [alertTitle, setAlertTitle] = useState();
const [alertOnPress, setAlertOnPress] = useState();
// ...
const winner = (theWinner) => {
setBlocked(true);
setAlertTitle(`${theWinner} win!`);
setAlertOnPress(() => setAlertVisible(!alertVisible));
setAlertVisible(true);
}
// ...
return (
<View style={styles.container}>
<RCModal title={alertTitle} visible={alertVisible} onButtonPress={alertOnPress} />
<ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }}>
<Text style={styles.title}>Noughts and Crosses</Text>
<Text style={styles.tip}>Get {winCondition()} in row, column or diagonal</Text>
<View style={styles.buttonsContainer}>
<Text style={styles.turnContainer}>Turn: <Text style={[styles.turn, { color: turn === 'X' ? '#2E86C1' : '#E74C3C'}]}>{turn}</Text></Text>
<TouchableHighlight underlayColor="#000000" style={[styles.button, styles.newGameButton]} onPress={setInitialFieldState}>
<Text style={styles.buttonText}>New game</Text>
</TouchableHighlight>
</View>
<Field state={fieldState} size={fieldSize} onCellPress={onCellPress} />
</ScrollView>
<View style={styles.settingsButtonContainer}>
<TouchableHighlight underlayColor={theme.colors.secondary} style={styles.settingsButton} onPress={onSettingsPress}>
<Image source={require('../img/settings.png')} style={styles.settingsIcon} />
</TouchableHighlight>
</View>
</View>
);
};
When the winner() is called, it is displayed as it should, but when I press OK button, it is not hiding. How can I fix it?
You can use setAlertVisible to change the alertVisible state:
<RCModal title={alertTitle} visible={alertVisible} onButtonPress={() => setAlertVisible(false)} />
The answer was that to set a function like a state variable, I needed to set it like
setAlertOnPress(() => () => setAlertVisible(false))
(2 x () =>)
I fetched the data from api, I could show the data in console but it did not dispaly in the application.I tried many ways but it still undisplayed inthe app.
this is how I fetched the api.
const [dataProduct,setDataProduct] = useState([]);
useEffect(() => {
getProductsApi();
},[])
const getProductsApi = async () => {
axios.get(productUrl)
.then((res) => {
// console.log(res.data)
setDataProduct(res.data)
}).catch(err => console.log(err))
// const response = await fetch(productUrl);
// const data = await response.json();
// try{
// setDataProduct(data);
// dataProduct.forEach(pro => {
// return(console.log(pro.title.rendered));
// })
// }catch(err) {
// console.log(err)
// }
}
there is where I am using the data I tried to cossole the dataProduct variable at first it display an empty array after seconds it show the data of api but still not diisplay on application
return (
<SafeAreaView style={productsCaS.C}>
<View style={productsCaS.warp}>
<Text style={productsCaS.txt}>مواد غذائية</Text>
<ScrollView
onScroll={({ nativeEvent }) => change(nativeEvent)}
showsHorizontalScrollIndicator={false}
pagingEnabled
horizontal
style={productsCaS.box}
bouncesZoom={true}
>
{dataProduct.forEach((product) => {
return(
<View style={{ width: phoneH.W(45), marginRight: phoneH.W(2.5) }}>
<TouchableOpacity style={productsCaS.box}>
<Image
source={{ uri: 'https://huzurshops.com/wp-content/uploads/2013/06/3a-300x300.jpeg' }}
style={productsCaS.img}
/>
<Button
buttonStyle={productsCaS.btn}
containerStyle={productsCaS.btn}
icon={
<Ikon is={'SimpleLineIcons'} i={'handbag'} s={24} />
}
iconRight={true}
title='اضافة الى السلة'
titleStyle={productsCaS.btnTxt}
/>
</TouchableOpacity>
<TouchableOpacity style={productsCaS.title}>
<Text style={productsCaS.titleTxt}> {product.title.rendered}</Text>
</TouchableOpacity>
<View style={productsCaS.iconBox}>
<Ikon is={'Entypo'} i={'star'} s={20} c={'yellow'} />
<Ikon is={'Entypo'} i={'star'} s={20} c={'yellow'} />
<Ikon is={'Entypo'} i={'star'} s={20} c={'yellow'} />
<Ikon is={'Entypo'} i={'star'} s={20} c={'yellow'} />
</View>
<Text style={productsCaS.price}>{product._price}</Text>
</View>
)})}
</SafeAreaView>
</View>
I am not sure how to add a delete function in a FlatList. I know I can make different components, but I want to know how to do it within this one file. I've trying to figure this out for hours, but do not know how to do.
export default function test() {
const [enteredGoal, setEnteredGoal] = useState("");
const [courseGoals, setCourseGoals] = useState([]);
const goalInput = enteredText => {
setEnteredGoal(enteredText);
};
const addGoal = () => {
setCourseGoals(currentGoals => [
...currentGoals,
{ key: Math.random().toString(), value: enteredGoal }
]);
};
const removeGoal = goalId => {
setCourseGoals(currentGoals => {
return currentGoals.filter((goal) => goal.id !== goalId);
})
}
return (
<View style={styles.container}>
<View>
<TextInput
color="lime"
style={styles.placeholderStyle}
placeholder="Type here"
placeholderTextColor="lime"
onChangeText={goalInput}
value={enteredGoal}
/>
</View>
<FlatList
data={courseGoals}
renderItem={itemData => (
<View style={styles.listItem} >
<Text style={{ color: "lime" }}>{itemData.item.value}</Text>
</View>
)}
/>
<View>
<TouchableOpacity>
<Text style={styles.button} onPress={addGoal}>
Add
</Text>
</TouchableOpacity>
</View>
</View>
);
}
You just need to modify your code a bit to handle the delete button. Since you already have delete functionality, call that function when you click the delete button. That's it.
<FlatList
data={courseGoals}
renderItem={itemData => (
<View style={{ flexDirection: "row", justifyContent: "space-between" }}>
<Text style={{ color: "lime" }}>{itemData.item.value}</Text>
<TouchableOpacity onPress={() => removeGoal(itemData.item.key)}>
<Text>Delete</Text>
</TouchableOpacity>
</View>
)}
/>;
EDIT
change your removeGoal function as below
const removeGoal = goalId => {
setCourseGoals(courseGoals => {
return courseGoals.filter(goal => goal.key !== goalId);
});
};
Hope this helps you. Feel free for doubts.