I am trying to make an e-commerce app and everything working only the cart icon counts not updating when the user adds an item to cart.
Here is my main page where i am calling component:
<Header headerTitle={this.state.wineD.name} lefticonType={'back'} navigation={this.props.navigation} />
Here is component code:
componentDidMount(){
//API code here and updating response count in state.
if(response.data.success){
this.setState({
cartItems: (response.data.data.cart.items != '' && (response.data.data.cart.items).length > 0)?
(response.data.data.cart.items).length : 0
})
this.props.changeLoaderStatus();
}
}
<FlatHeader
leftIcon={<Icon name={leftIcon} size={20} color="#FFF" />}
leftIconHandler={() => {
(this.props.lefticonType == 'bars' ?
this.props.navigation.dispatch(DrawerActions.openDrawer())
: goBack())
}}
centerContent={
<View style={{width: width*0.7,alignItems:'center'}}>
<Text numberOfLines={1} style={{ color: '#FFF',fontSize:22,fontWeight:'bold' }}>{this.props.headerTitle}</Text>
</View>
}
rightIcon={<Group><Icon name="shopping-cart" size={20} color="#FFF" />
<View style={{width:16,height:16,borderRadius:8,backgroundColor:'red',justifyContent:'center',
alignItems:'center',marginBottom:14}}>
<Text style={{fontSize:10,color:'#fff',fontWeight:'bold'}}>{this.state.cartItems}</Text></View></Group>}
rightIconHandler={() => this.props.navigation.navigate('Cart')}
large
style={{ backgroundColor: '#d7b655' }}
/>
This is the screen where from other component updating the cart
Anyone have solution please share here.
If I understood correctly your problem, you may need to modify this.setState in this way:
componentDidMount(){
//API code here and updating response count in state.
if(response.data.success){
this.setState({
cartItems: (response.data.data.cart.items != '' && (response.data.data.cart.items).length > 0)?
(response.data.data.cart.items).length : 0
},()=>{
this.props.changeLoaderStatus(); }) } }
try this and let me know if it works for you.
Related
I have a map and i want a marker to appear when the user long-presses on a point.
I have the following code:
const [coords, setcoords] = React.useState(getcoord());
const [show, setShow] = React.useState(false);
const setPointCoords = (e) => {
setcoords(e.geometry.coordinates);
setShow(!show);
}
return (
<View style={style.page}>
<MapboxGL.MapView
style={style.map}
rotateEnabled={false}
styleURL="mapbox://styles/daskalgg/ckp26fbmb34iv18otkav9sj4s"
onLongPress={(e) => {
setPointCoords(e);
}}
>
{
show &&
<MapboxGL.PointAnnotation
key="marker"
id="point"
draggable={true}
coordinate={coords} />
}
</MapboxGL.MapView>
{
show &&
<Text>test</Text>
}
</View>
);
The problem i have is that, although setPointCoords is called and the value of show changes, the marker never appears.
Some things i have noticed:
The Text element, which is there for testing purposes, works as expected.
The problem goes away when the initial value of show is true.
Try this out
{show ? (
<MapboxGL.PointAnnotation
key="marker"
id="point"
draggable={true}
coordinate={coords}
/> )
: null}
I found a solution but it's pretty hacky
<MapboxGL.PointAnnotation
key="marker"
id="point"
draggable={true}
onSelected={(e) => {
console.log(e);
}}
coordinate={coords} >
<View
key="marker"
style={{
borderColor: "black", backgroundColor: "red",
display: show ? 'flex' : 'none'
}}
>
<Text> This is a Marker </Text>
</View>
</MapboxGL.PointAnnotation>
Since i can't control the style of the PointAnnotation itself, i display a View and control it's visibility through 'show'. I am not accepting it as the correct answer yet in hopes there is a better one.
I am currently working with algolia and I am trying to show the data on my app, there are over 37 products in my DB and I would like to display them in my app. I want to display 15 items on a single page and then pressing the next button it will show the next 15,
I have currectly manage to connect my react app to algolia, and see the data, however I can not manage to display 15 items and then by pressing next it will just show the next 15.
My Hit component looks like this:
function InfiniteHits({ hits, hasMore, refine }) {
return (
<View>
<View>
<FlatList
style={{
width: Platform.OS === "ios" ? 380 : 400,
}}
data={hits}
keyExtractor={(item) => item.objectID}
ItemSeparatorComponent={() => <View style={styles.separator} />}
onEndReached={() => hasMore && refine()}
renderItem={({ item }) => (
<View style={styles.item}>
// here i render the data so when I clik on any of them it opens it in the modal
</View>
)}
/>
</View>
</View>
);
}
InfiniteHits.propTypes = {
hits: PropTypes.arrayOf(PropTypes.object).isRequired,
hasMore: PropTypes.bool.isRequired,
refine: PropTypes.func.isRequired,
};
export default connectInfiniteHits(InfiniteHits);
then in my app I have:
<InstantSearch searchClient={searchClient} indexName="name of db">
<SearchBox />
<ConnectedPagination padding={2} />
<Hits />
</InstantSearch>
and for my Pagination I have:
const range = (start, end) =>
Array.from({ length: end - start + 1 }, (_, i) => start + i);
const Pagination = ({ padding = 3, refine, currentRefinement, nbPages }) => (
<View
style={{
flexDirection: "row",
justifyContent: "space-around",
}}
>
<TouchableOpacity onPress={() => refine(1)}>
<Text>first</Text>
</TouchableOpacity>
{range(
Math.max(1, currentRefinement - padding),
Math.min(nbPages, currentRefinement + padding)
).map((page) => (
<TouchableOpacity
key={page}
onPress={() => refine(page)}
style={{
color: currentRefinement === page ? "red" : "unset",
}}
>
<Text>{page}</Text>
</TouchableOpacity>
))}
<TouchableOpacity onPress={() => refine(nbPages)}>
<Text>last</Text>
</TouchableOpacity>
</View>
);
const ConnectedPagination = connectPagination(Pagination);
it correctly calculates the number of pages, and display them (in another db of mine there will more than 20 pages) however app still shows all the data below, and when I search for something I can see that it changes the number of pages, but when I click on it it wont do anything, so the question is how can I display few items per page and using the pagination just move through them?
the documentation comes with hitperpage, pagination and scrollto, they have a component and also a widget as well, I am not quit sure how to use them, I am a bit confused when looking at the tutorial.
Oki I figured it out in some ways, I am using InfiniteHits here, which displays all the data from the DB and if you want to use Pagination and go through pages in your app instead of InfiniteHits you have to use Hits. This is what fixed it for me.
I've been searching for a few days to solve this problem. I need to change another icon's color when i click in one of them.
I'm using react-native-vector-icons
this.setState({
listaPlantel: Object.entries(dataArray).map(function ([key, nome]) {
if (that.state.mercado.status_mercado == 2) {
dadosAtleta = that.state.pontuados[nome.atleta_id];
}
return (
<ListItem avatar key={key} button onPress={() => that.detailsScreen(nome)}>
<Left>
<Thumbnail source={{ uri: nome.foto.replace('FORMATO', '80x80') }} />
</Left>
<Body>
<Text>{nome.apelido}</Text>
<Text note>{that.state.posicoes ? that.state.posicoes[nome.posicao_id]['nome'] : ''} - {that.state.clubes ? that.state.clubes[nome.clube_id]['nome'] : ''}</Text>
<Text style={{ textAlign: 'left' }}>Última: {nome.pontos_num} Média: {nome.media_num} {' $' + nome.preco_num}</Text>
</Body>
<Right>
{/*<Text>{dadosAtleta ? dadosAtleta['pontuacao'] : nome.pontos_num}</Text>*/}
<Icon name="md-close-circle" size={30} />
<Icon type="Foundation" name="md-contact" key={key} size={30} color={that.state.id_capitao === nome.atleta_id ? that.state.corCap : that.state.corGeral} onPress={() => that.setState({ id_capitao: nome.atleta_id })} />
</Right>
</ListItem>
)
}),
});
It seems you are putting conditions and functions within setState I would recommend you read about the lifecycle and app state here:
https://reactjs.org/docs/state-and-lifecycle.html
As an example of how to update values, of which you're trying to do - take this scenario into consideration:
initial colour : red, updated colour : blue (For example)
in your constructor:
constructor (props) {
super(props);
this.state = {
/*Initial State and Colour*/
iconColour : "red"
}
}
in your render method:
<ListItem avatar key={key} button onPress={() => that.detailsScreen(nome)}>
<Icon color={this.state.iconColour}/>
</ListItem>
Within your onPress function:
this.setState({
iconColor : "blue"
})
My child component is below
export default function PickerList ({headingText,listData,hideView,finalpickedItem,onItemSelected,selected} ) {
const {modalHolder,modalHeader,modalHeaderText,modalBody,PerListView,PerListVie wText,okCancel,okCancelHolder,PerListViewActive,
} = styles;
return(
<View style={modalHolder}>
<View style={modalHeader}>
<Text style={modalHeaderText}>{headingText}</Text>
</View>
<View style={modalBody}>
<FlatList data={listData} renderItem={({item , index}) =>
<TouchableOpacity
onPress={() => {
{headingText === 'name'?
onItemSelected(item.name)
: headingText === 'Time' ?
onItemSelected(item.time)
: headingText === 'Property'
onItemSelected(item.property)
}
}}
style={{width:'100%',}}
>
<View
style={
selected===item.name ? PerListViewActive : PerListView > // here i am not getting active hot reload making it active
<Text style={PerListViewText}>
{item.name }
</Text></View>
</TouchableOpacity>
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
</View>
);
};
PickerList.propTypes = {
onItemSelected: PropTypes.func.isRequired,
};
and my parent is
onMenuItemSelected = item => {
console.log(item); // i am getting here selected item
this.setState({ commonSelected: item }); // i am getting final state also.
}
<PickerList
headingText="Property"
listData = {this.state.property_type_options}
hideView = {()=>{this.hideView()}}
finalpickedItem = {()=>{this.finalpickedItem()}}
onItemSelected={this.onMenuItemSelected}
selected = {this.state.commonSelected} /// i have final value here also
/>
issue is "selected" not working every thing is working fine .. selected working but after a hot reload. can i re-render module. state is updating fine but it is not getting active.
I found my answer this is very nice.
extraData={this.state}
I am creating react native app. on app category page i am fetching data and from live url in json form and post it into product page.
fetching data code:-
handlePressProduct(id) {
var url='http://www.furnitureinfashion.net/menu_category_listing.php?cat_id=';
fetch(url+id, {
method: 'GET'
}).then((response) => { return response.json() } )
.then((responseJson) => {
console.log(responseJson);
Actions.product({data:responseJson})
})
}
on product page i am getting data like this:-
{this.props.data.map((dataImage,Index1)=>
<View key={Index1}>
{dataImage['ProductId'] != undefined && (
<View style={productStyle.homeimg1}>
<TouchableOpacity onPress={this.handlePressProduct.bind(this,dataImage['ProductId'])}>
<Image source={{uri: uri+dataImage['Image']}} style={{width: 130, height: 130}} />
<Text style={productStyle.title}> {dataImage['ProductName']}</Text>
<Text style={productStyle.shopbutton}>View Details</Text>
</TouchableOpacity>
{dataImage['Options'] != '' &&(
<Text style={productStyle.cartbutton} >Select Option</Text>
)}
{dataImage['Options'] == '' &&(
<Text style={productStyle.cartbutton} >Add to cart</Text>
)}
<Text> RRP{dataImage['RRPPrice']}</Text>
<Text> Our Price{dataImage['OurPrice']}</Text>
<Text style={productStyle.buymorebutton} >Buy & Save More Today</Text>
<Text style={productStyle.shiptext} >Free Shipping</Text>
</View>
)}
</View>
)}
in array product data is too large so, i want to add pagination on product page. but i don't know how to do?