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>
Related
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>
);
i'm working with my project using react native and firestore, i'm trying to get document from my collection 'requests' by uid that have the same uid with current logged in user and after retrieve it show the data but i got an error TypeError: docs.forEach is not a function. Previously i have successfully add the document to collection with current logged in user uid. Here is my code
constructor() {
this.state={
requests:[]
}
}
componentDidMount(){
this.fetchRequests();
}
fetchRequests(){
this.subscriber = firebase.firestore()
.collection("requests").doc(firebase.auth().currentUser.uid).onSnapshot(docs => {
let requests = []
docs.forEach(doc => {
requests.push(doc.data())
})
this.setState({requests})
})
}
buildPanels() {
if (this.state.requests.length !== 0) {
return this.state.requests.map((req, idx) => {
return <View key={idx} style={styles.panel}>
<View style={{flex: 1}}>
<View style={styles.panelRow}>
<Text style={styles.panelText}>Name</Text>
<Text style={styles.panelText}>{req.name}</Text>
</View>
<View style={styles.panelRow}>
<Text style={styles.panelText}>Blood Type</Text>
<Text style={{flex: 0.5}}>{req.golDarah}</Text>
</View>
<TouchableOpacity onPress={this.deleteData}>
<Text style={{color:color.red}}>End Request</Text>
</TouchableOpacity>
</View>
</View>
</View>
</View>
});
}
else{
return <View>
<Text style={{fontSize: fontSize.regular + 1, color: color.red}}>you dont have request</Text>
</View>
}
}
render(){
return(
{this.buildPanels()}
)
}
when you select firebase.firestore.collection('your collection').get() you're allowed use forEach because you will loop documents. Your question you get a 'Specific Document' so you don't have document to loop.
In your case
firestore()
.collection("requests")
.doc(firebase.auth().currentUser.uid)
.get()
.then(docs => {
if (docs.exists) {
console.log('requests data: ', docs.data());
}
});
i'm beginner of react-native. help me haha...
i give a useState data ('playlist') from MainPage.js to playList.js
in MainPage.js
const [playList, setPlayList] = useState([]);
<TouchableOpacity onPress={() => navigate('PlayList', {data: playList})}>
in playList.js
const Imagetake = ({url}) => {
url =url.replace('{w}', '100');
url = url.replace('{h}', '100');
return <Image style ={{height:'100%', width:'100%'}} source ={{url:url}}/>
};
const PlayList = ({ navigation }) => {
const playList = navigation.getParam('data');
const setPlayList = navigation.getParam('setData');
const deletePlayList = (data) => {
setPlayList(playList.filter((song)=> song.id != data.id));
};
return (
<View style={styles.posts}>
<FlatList
data={playList}
keyExtractor={posts => posts.id}
renderItem={({item}) =>{
return (
<View>
<TouchableOpacity onPress={() => deletePlayList( item )}>
<Ionicons name="trash-outline" size={30}/>
</TouchableOpacity>
<TouchableOpacity>
<View style={styles.post}>
<View style ={styles.postcontent}>
<Imagetake url={item.attributes.artwork.url}></Imagetake>
</View>
<View style={styles.posthead}>
<View style = {styles.postheadtext}>
<Text style ={styles.posttitletext}>{item.attributes.name}</Text>
<Text style={styles.username}>{item.attributes.artistName}</Text>
</View>
<View style = {styles.postheadtext2}>
<Text style={styles.username}>{item.attributes.albumName}</Text>
</View>
</View>
</View>
</TouchableOpacity>
</View>
)
}}
/>
</View>
);
};
when i delete some songs in playList, it is well done in playList page. but when i go to mainpage and go to playList again, delete is useless. the songs that i deleted before is refreshed. how can i fix it? T^T
You may also pass the setPlayList function to PlayList page.
And instead of creating another useState in the child page, you directly call the setPlayList that is passed from parent page
So I've seen many posting the same problem, but for some I don't seem to be able to adapt the posted solutions to my case.. I hope someone can tell me exactly what changes I need to do in order to get this working, since I don't know how to implement the suggested solutions!
I am using React Native Swipeable
Example of someone having the same issue
I have a file in which I built the Swipeable Component and an other class which calls the component. I've set a timeout close function on the onSwipeableOpen as a temporary solution. But ideally it should close immediately upon pressing "delete". The "..." stands for other code which I deleted since it's not important for this case.
AgendaCard.js
...
const RightActions = ({ onPress }) => {
return (
<View style={styles.rightAction}>
<TouchableWithoutFeedback onPress={onPress}>
<View style={{ flexDirection: "row", alignSelf: "flex-end" }}>
<Text style={styles.actionText}>Löschen</Text>
<View style={{ margin: 5 }} />
<MaterialIcons name="delete" size={30} color="white" />
</View>
</TouchableWithoutFeedback>
</View>
);
};
...
export class AgendaCardEntry extends React.Component {
updateRef = (ref) => {
this._swipeableRow = ref;
};
close = () => {
setTimeout(() => {
this._swipeableRow.close();
}, 2000);
};
render() {
return (
<Swipeable
ref={this.updateRef}
renderRightActions={() => (
<RightActions onPress={this.props.onRightPress} />
)}
onSwipeableOpen={this.close}
overshootRight={false}
>
<TouchableWithoutFeedback onPress={this.props.onPress}>
<View style={styles.entryContainer}>
<Text style={styles.entryTitle}>{this.props.item.info}</Text>
<Text style={styles.entryTime}>
eingetragen um {this.props.item.time} Uhr
</Text>
</View>
</TouchableWithoutFeedback>
</Swipeable>
);
}
}
Agenda.js
...
renderItem(item) {
...
<AgendaCardAppointment
item={item}
onRightPress={() => firebaseDeleteItem(item)}
/>
...
}
I'm having the same issue and have been for days. I was able to hack through it, but it left me with an animation I don't like, but this is what I did anyways.
export class AgendaCardEntry extends React.Component {
let swipeableRef = null; // NEW CODE
updateRef = (ref) => {
this._swipeableRow = ref;
};
close = () => {
setTimeout(() => {
this._swipeableRow.close();
}, 2000);
};
onRightPress = (ref, item) => { // NEW CODE
ref.close()
// Delete item logic
}
render() {
return (
<Swipeable
ref={(swipe) => swipeableRef = swipe} // NEW CODE
renderRightActions={() => (
<RightActions onPress={() => this.onRightPress(swipeableRef)} /> // NEW CODE
)}
onSwipeableOpen={this.close}
overshootRight={false}
>
<TouchableWithoutFeedback onPress={this.props.onPress}>
<View style={styles.entryContainer}>
<Text style={styles.entryTitle}>{this.props.item.info}</Text>
<Text style={styles.entryTime}>
eingetragen um {this.props.item.time} Uhr
</Text>
</View>
</TouchableWithoutFeedback>
</Swipeable>
);
}
}
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.