React-Redux | Productlist | Add/Remove w/ BindActionCreator - reactjs

I'm trying to create an product list in React where I can add and remove products.
I started to do some research on how I could do this using the redux framework/platform and react native
I already have an function productList container, product component and cartList, cartProduct component.
My problems are:
Products: I can only add products and not remove
Cart: Vice versa + the cart does not get updated on the status of the cart items.
I've added bindActionCreator but don't know how to apply it to my productList yet.
What do I expect to happen?
I'm trying to add and remove products from the react store in the same container/component.
How can I do this? Is my approach correct or am I completely wrong ?
A thank you in advance.
ProductActionCreators
export const ADD_TO_CART = 'ADD_TO_CART'
export const REMOVE_FROM_CART = 'REMOVE_FROM_CART'
export function addItemToCart(row) {
return {
type:'ADD_TO_CART',
payload: row, qty
}
}
export function removeTodo(row) {
return {
type:'REMOVE_FROM_CART' ,
payload: row, qty
}
}
ProductList(simplified)
import React from 'react';
import { Component } from 'react';
import {
View,
StyleSheet,
Text
} from 'react-native';
import Products from '../components/Products';
import { bindActionCreators} from 'redux';
import { connect } from 'react-redux';
import * as ProductActionCreators from '../actions/ProductActionCreators'
export class ProductList extends React.Component {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
const { rows } = this.props.navigation.state.params;
const arrays = Object.values( {rows});
this.state = {
arrays,
filteredProducts: arrays,
};
const { dispatch } = props
this.boundActionCreators = bindActionCreators(ProductActionCreators, dispatch)
console.log(this.boundActionCreators)
}
render() {
return (
<View style={styles.container} >
<Text style={styles.title} >
{this.state.arrays[0].name}
</Text>
<Products products={this.state.arrays[0].data} onPress=
//Trying to change this to multiple actions
{this.props.addItemToCart}/>
</View>
)
}
}
const qty = 0;
const mapDispatchToProps = (dispatch) =>{
//need to add BindActionCreator
return{
addItemToCart:(row) => dispatch({
type:'ADD_TO_CART', payload: row, qty
}),
removeItem:(product) => dispatch ({
type:'REMOVE_FROM_CART' , payload: product, qty
})
}
}
export default connect(null, mapDispatchToProps) (ProductList);
Product(simplified)
import React, { Component } from "react";
import {
View,
Text,
TouchableOpacity,
TextInput,
FlatList,
} from "react-native";
import Icon from "react-native-vector-icons/Ionicons";
class Products extends Component {
constructor(props) {
super(props);
const { products } = this.props;
this.state = {
products,
filteredProducts: products,
};
}
renderProducts = (products) => {
return (
<View key={products.index}>
<View>
<Icon name={products.item.icon} color="#DD016B" size={25} />
</View>
<View>
<Text style={styles.name}>
{products.item.name}
</Text>
<Text>
€ {products.item.price}
</Text>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={() => this.props.onPress(products.item)} >
<Icon name="ios-add" color="white" size={25} />
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.onPress(products.item)} >
<Icon name="ios-remove" color="white" size={25} />
</TouchableOpacity>
</View>
</View>
)
}
render() {
return (
<View>
<FlatList
style={styles.listContainer}
data={this.state.filteredProducts}
renderItem={this.renderProducts}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
export default Products;
reducers/cartItems
const cartItems = (state = [], action) => {
switch (action.type)
{
case 'ADD_TO_CART':
if (state.some(cartItem => cartItem.id === action.payload.id)) {
// increase qty if item already exists in cart
return state.map(cartItem => (
cartItem.id === action.payload.id ? { ...cartItem, qty: cartItem.qty + 1 } : cartItem
));
}
return [...state, { ...action.payload, qty: 1 }];
// else add the new item to cart
case 'REMOVE_FROM_CART':
return state
.map(cartItem => (cartItem.id === action.payload.id ? { ...cartItem, qty: cartItem.qty - 1 } : cartItem))
.filter(cartItem => cartItem.qty > 0);
}
return state
}
export default cartItems
store/Index
import {createStore} from 'redux';
import cartItems from '../reducers/carItems';
export default store = createStore(cartItems)
App structure (simplified)
Main folder
↳
Containers(folder)
↳
ProductsList.js
CartList.js
Components(folder)
↳
Product.js
cartProduct.js
Reducers(folder)
↳
carItems.js
Actions(folder)
↳
ProductActionCreators.js
Navigation(folder)
↳
AppNavigator,js
MainTabNavigator.js
Assets(folder for images etc.)
Store(folder)
↳
index.js
App.JS
Data.JS (using static JSON file for this development phase)

You have two different actions, addItemToCart, removeItem which you define in mapDispatchToProps. Now that you specify a mapDispatchToProps argument to connect, the dispatch method is not available as a prop to the connected component, instead the method returns by mapDispatchToProps are only available
Second, you don't need to use bindActionCreators and definitely not in the component. MapDispatchToProps can simply be an object and connect will use dispatch internally.
Third, you need to pass the add and remove actions both to the child component.
Fourth you can pass multiple actions on to Product component simply as prop
Your code would look like
ProductActionCreators.js
export const ADD_TO_CART = 'ADD_TO_CART'
export const REMOVE_FROM_CART = 'REMOVE_FROM_CART'
export function addItemToCart(row) {
return {
type:'ADD_TO_CART',
payload: row
}
}
export function removeItem(item) {
return {
type:'REMOVE_FROM_CART' ,
payload: item
}
}
ProductList
import React from 'react';
import { Component } from 'react';
import {
View,
StyleSheet,
Text
} from 'react-native';
import Products from '../components/Products';
import { connect } from 'react-redux';
import { addItemToCart, removeItem } from '../actions/ProductActionCreators';
export class ProductList extends React.Component {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
const { rows } = this.props.navigation.state.params;
const arrays = Object.values( {rows});
this.state = {
arrays,
filteredProducts: arrays,
};
}
render() {
return (
<View style={styles.container} >
<Text style={styles.title} >
{this.state.arrays[0].name}
</Text>
<Products products={this.state.arrays[0].data} addItemToCart={this.props.addItemToCart} removeItem={this.props.removeItem}/>
</View>
)
}
}
const mapDispatchToProps = {
addItemToCart,
removeItem
}
export default connect(null, mapDispatchToProps) (ProductList);
Product
import React, { Component } from "react";
import {
View,
Text,
TouchableOpacity,
TextInput,
FlatList,
} from "react-native";
import Icon from "react-native-vector-icons/Ionicons";
class Products extends Component {
constructor(props) {
super(props);
const { products } = this.props;
this.state = {
products,
filteredProducts: products,
};
}
renderProducts = (products) => {
return (
<View key={products.index}>
<View>
<Icon name={products.item.icon} color="#DD016B" size={25} />
</View>
<View>
<Text style={styles.name}>
{products.item.name}
</Text>
<Text>
€ {products.item.price}
</Text>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={() => this.props.addItemToCart(products.item)} >
<Icon name="ios-add" color="white" size={25} />
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.removeItem(products.item)} >
<Icon name="ios-remove" color="white" size={25} />
</TouchableOpacity>
</View>
</View>
)
}
render() {
return (
<View>
<FlatList
style={styles.listContainer}
data={this.state.filteredProducts}
renderItem={this.renderProducts}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
export default Products;

Code looks alright for most part.
The react-redux connect part in ProductList looks off. qty is always 0. It should be 1.
Also, mapStateToProps should be present to get the products from the cart.

In your ProductList, I'd approach the action binding like so:
const mapDispatchToProps = (dispatch) =>{
return bindActionCreators({
addItemToCart: (row, qty) => dispatch({
type:'ADD_TO_CART', payload: {row, qty}
}),
removeItem: (product, qty) => dispatch({
type:'REMOVE_FROM_CART' , payload: {product, qty}
})
})
}
export default connect(null, mapDispatchToProps)(ProductList);
Remove the action binding from your component's constructor as that's unnecessary.
You may want to split the code out into a Container/Component/ HOC approach, as I find it makes code far easier to read. As you've defined your actions in separate file, I'd also import these rather than redeclaring them.
If you follow this advice, you'd end up with the following:
container.js
import { bindActionCreators } from 'redux';
import ProductList from './product-list';
// Actions
import { addItemToCart, removeItem } from './actions';
function mapStateToProps(state) {
return {}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
addItemToCart,
removeItem,
})
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductList);
product-list.js
import React from 'react';
import { View, Text } from 'react-native';
import Products from '../components/Products';
export class ProductList extends React.Component {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
const { rows } = this.props.navigation.state.params;
const arrays = Object.values( {rows});
this.state = {
arrays,
filteredProducts: arrays,
};
this.handleProductPress = this.handleProductPress.bind(this);
}
handleProductPress(e) {
e.preventDefault();
// This is pseudo code...
this.props.addItemToCart(e.target.value, 1);
return;
}
render() {
return (
<View style={styles.container} >
<Text style={styles.title} >
{this.state.arrays[0].name}
</Text>
<Products products={this.state.arrays[0].data} onPress={this.handleProductPress} />
</View>
)
}
}
export default ProductList;
Have a play with that and see how you get on.

Related

How to dispatch state in class component using React-redux?

I'm trying to get my head around Redux.
Here's the MainMap.js:
import React from 'react';
import {
TouchableWithoutFeedback,
StyleSheet,
Keyboard,
PermissionsAndroid,
Platform,
View,
Button,
FlatList,
Dimensions,
TouchableOpacity,
Text
} from 'react-native';
import * as placeAction from '../../store/actions/place/place';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
class MainMap extends React.Component{
constructor(props){
super(props);
this.state={
//....
destinationName: [],
destinationAddress: [],
//...
};
//......
this.addPlaceHandle = this.addPlaceHandle.bind(this)
};
//....
// Dispatch a place
addPlaceHandle(name, address){
this.props.addingPlace(name, address);
}
render(){
const {container, map, listOfSearchBars, buttonView, button, next} = styles
const { destinationCoords, userLatitude, userLongitude, initial_UserLatitude, initial_UserLongitude } = this.state;
//....
return(
<TouchableWithoutFeedback onPress={this.hideKeyboard} >
<View style={container} >
<View style={buttonView}>
<TouchableOpacity style={button} onPress={() => {
this.addPlaceHandle(this.state.destinationName, this.state.destinationAddress);
}}>
<Text style={next}>Next</Text>
</TouchableOpacity>
</View>
</View>
</View>
</TouchableWithoutFeedback>
)
}
componentWillUnmount(){
Geolocation.clearWatch(this.watch_location_id);
}
}
//}
const styles = StyleSheet.create({
container:{
flex: 1
},
map:{
...StyleSheet.absoluteFillObject
},
listOfSearchBars:{
...
},
buttonView:{
...
},
button:{
...
},
next: {
...
}
});
const mapDispatchToProps = (dispatch) => ({
addingPlace: (_name, _address) => dispatch(placeAction.addPlace(_name, _address))
})
export default connect(null, mapDispatchToProps)(MainMap)
Basically, the MainMap.js is like Google Map. You search a location, choose it from the suggestions, and it'll show the direction for you.
After loads of async/await functions and this.setState(), the name and the address from the location we choose will be added to the this.state.destinationName and this.state.destinationAddress, respectively.
I've successfully done that. Now I want to dispatch that data which is the name & address to the store
place.js in actions:
export const ADD_PLACE = 'ADD_PLACE';
export const addPlace = (name, address) => {
return {
type: ADD_PLACE,
placeData: {
name: name,
address: address
}
};
};
Here's the place.js in reducers:
import { ADD_PLACE } from '../../actions/place/place';
import Place from '../../../src/models/place';
const initialState = {
places: []
};
export default (state = initialState, action) => {
switch(action.type){
case ADD_PLACE:
const newPlace = new Place(
action.placeData.name,
action.placeData.address
);
return {
places: state.places.concat(newPlace)
};
default: return state;
}
}
But I get this error when I click the button:
Any answers and recommended resources are deeply appreciated !
The problem is I did import the Place incorrectly
It has to be:
import {Place} from ''
Thanks #hussain for helping me

passing textinput value from one screen into another using mapDispatchToProps

I want to pass value of a textinput from one screen to another using mapDispatchToProps. I am roughly a newbie in the redux world and I am a bit confused. kindly make corrections to my code below. I have tried using the example implemented on the documentation, however, I do not fully understand mapDispatchToProps.
PS I tried to keep the code as simple as possible for better understanding
Screen1
import React, { Component, Fragment } from 'react';
import {
View,
Text,
StyleSheet,
} from 'react-native';
import { connect } from 'react-redux';
class Screen1 extends Component {
static navigationOptions = {
header: null,
}
constructor(props) {
super(props);
this.state = {
total: 1,
};
this.onChangeText = this.onChangeText.bind(this);
}
onChangeText(number) {
const total = parseInt(number);
if (number.length === 0) {
this.setState({ total: '' });
} else {
this.setState({ total });
}
}
render() {
return (
<SafeAreaView style={styles.AndroidSafeArea}>
<View style={styles.wrapper}>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={styles.scrollableList}
>
<InputField
children={"Receiver's phone no."}
iconType={'ios-call'}
placeholder={"number"}
keyboardType={'phone-pad'}
maxLength={11}
/>
<InputField
children={"Receiver's gifts"}
iconType={'ios-basket'}
placeholder={'Gifts'}
keyboardType={'phone-pad'}
maxLength={2}
onChangeText={this.onChangeText}
value={this.state.total.toString()}
/>
</ScrollView>
</View>
</SafeAreaView>
);
}
}
function mapDispatchToProps(dispatch) {
return {
total: () => {
dispatch(this.onChangeText());
}
}
}
export default connect(mapDispatchToProps) (Screen1);
Screen2
import React, { Component, Fragment } from 'react';
import {
View,
Text,
StyleSheet,
} from 'react-native';
import { connect } from 'react-redux';
class Screen2 extends Component {
static navigationOptions = {
header: null,
}
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<SafeAreaView style={styles.AndroidSafeArea}>
<View style={styles.wrapper}>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={styles.scrollableList}
>
<Text>{this.props.onChangeText}</Text>
</ScrollView>
</View>
</SafeAreaView>
);
}
}
function mapStateToProps(state) {
return {
total: state.onChangeText
}
}
}
export default connect(mapStateToProps) (Screen2);
Reducer.js
import { TOTAL_GIFTS } from '../actions/types';
const initialState = {
total: ''
};
const Reducer = (state = initialState, action) => {
switch (action.type) {
case TOTAL_GIFTS:
return {
...state,
total: action.total
};
default:
return state;
}
};
export default Reducer;
Im leaving the none redux related parts of your code out.
Screen1
class Screen1 extends React.component{
handleChange(number){
this.props.announceChange(number)
}
}
//mapping dispatch to props
function mapDispatchToProps(dispatch){
announceChange(number)
}
//action creator
function announceChange(number){
return {type:'SOME_CONSTANT',payload:number}
}
export default connect(null,mapStateToProps)(Screen1)
Reducer:
export default function reducer(state={},action){
switch(action.type){
case 'SOME_CONSTANT':
return {...state,number:action.payload}
default :
return state;
}
}
screen2:
class Screen2 extends React.component{
render(){
const {number} = this.props
return(
<span>{number}</span>
)
}
}
function mapStateToProps(state){
return {
number : state.reducername
}
}
export default connect(mapStateToProps)(Screen2);
the above code is a minimal sample of the way you can use redux. if you dont have any ideas how to setup your store,reducer and other redux stuff reading this wont take more than 10 mints.
mapDispatchToProps: are functions/actions to update store(redux)
mapStateToProps : to get data from store(redux)
on first screen you will disptach action to update email using mapDispatchToProps
on second you will get email from mapStateToProps
I have created a sample code for you (CHECK IN ANDROI/IOS)
Please check https://snack.expo.io/#mehran.khan/reduxtest
APP PREVIEW

React Native wont render next array items at setState

Hello I am trying to make a step wizard component but I have the following issue. I have the following file:
import React from 'react';
import { View } from 'react-native';
import WizardStep from './WizardStep'
export default class Wizard extends React.Component {
constructor(props){
super(props);
this.state = {
questions: this.props.questions,
answers: this.props.answers,
totalSteps: this.props.questions.length,
currentStep: 0,
results: []
}
}
updateStep = answer => {
newResults = this.state.results
newResults[this.state.currentStep - 1] = answer
this.setState({
results: newResults,
currentStep: this.state.currentStep + 1
}, () => {
if (this.state.currentStep == this.state.totalSteps) {
this.props.finish();
}
})
}
renderStep = () => {
if (this.state.currentStep < this.state.totalSteps) {
return (
<View>
<WizardStep
question={this.state.questions[this.state.currentStep]}
answers={this.state.answers[this.state.currentStep]}
step={this.state.currentStep}
totalSteps={this.state.totalSteps}
updateStep={this.updateStep}
/>
</View>
);
} else {
return null;
}
}
render(){
return(
<View>
{this.renderStep()}
</View>
)
}
}
questions is an array of strings and answers is an array of arrays of strings.
Anyway the first screen shows up just fine. But when I call the updateStep function the currentStep updates but it doesn't show the 2nd item from questions/answers array. Any ideas? Thank you in advance!
Adding the other components for the wizard:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Button } from "react-native-elements";
import { Constants } from 'expo';
import WizardStepButton from './WizardStepButton';
export default class WizardStep extends React.Component {
constructor(props){
super(props);
this.state ={
question: this.props.question,
answers: this.props.answers,
totalSteps: this.props.totalSteps,
step: this.props.step,
}
}
renderAnswers = () => {
var answers = []
for (var i = 0; i < this.state.answers.length; i++) {
answers.push(
<WizardStepButton
answer={this.state.answers[i]}
updateStep={this.props.updateStep}
key={i}
/>
);
}
return answers;
}
render(){
return(
<View>
<Text style={styles.title}>Step {this.state.step + 1}/{this.state.totalSteps}</Text>
<Text style={styles.title}>{this.state.question}</Text>
{this.renderAnswers()}
</View>
)
}
}
const styles = StyleSheet.create({
title: {
marginTop: 30,
marginBottom: 30,
fontSize: 25,
color: 'rgba(96,100,109, 1)',
lineHeight: 24,
textAlign: 'center',
},
});
and the button component:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Button } from "react-native-elements";
import { Constants } from 'expo';
export default class WizardStepButton extends React.Component {
constructor(props){
super(props);
this.state ={
}
}
render(){
return(
<View>
<Button
style={{margin: 10}}
large
raised
title={this.props.answer}
onPress={() => this.props.updateStep(this.props.answer)}
/>
</View>
)
}
}
You should only increment state values by using a state updater function. - https://stackoverflow.com/a/45196079/874027
You're not spreading this.state.results before editing and putting them back into state.
Also the currentStep checks indexing looks off.
updateStep = answer => {
this.setState((state) => {
const { results, currentStep } = state
const newResults = [...results]
newResults[currentStep] = answer
return {
results: newResults,
currentStep: currentStep + 1,
}
}, () => {
const { currentStep, totalSteps } = this.state
if (currentStep + 1 === totalSteps) {
this.props.finish();
}
})
}
EDIT: in WizardStep component you're syncing props with state in constructor so when you try to pass the new props after you update your state, they'll never get reflected in the Wizard since its constructor has already fired off. You can either fix this by using props in your WizardStep component, or by passing it a key, so the new instance gets created every time the key changes, e.g.
<WizardStep
question={this.state.questions[this.state.currentStep]}
answers={this.state.answers[this.state.currentStep]}
step={this.state.currentStep}
totalSteps={this.state.totalSteps}
updateStep={this.updateStep}
key={this.state.currentStep}
/>
I've tested this locally and the steps do get changed with this approach.

React with Redux: Child component does not rerender after props have changed (even though they are not shallow equal)

I'm building an app with React Native using Redux for the state management. I will post my code for all the involved components and the reducer down below, but since that is going to be much, let me describe the problem in a few sentences first.
I have an immutable reducer for my objects called 'waitercalls'. I have a screen (HomeScreen) that renders two components. Each component is a <FlatList /> of objects. The objects (waitercalls) are given to them via props by it's parent (HomeScreen). HomeScreen is connected to Redux via React-Redux' connect() and gets the objects ('waitercalls') via a selector created with Re-Select.
The left list's items can be pressed and upon press dispatch an event to the reducer. Here comes the problem. When the left list's item are pressed, the left list correctly updates (calls render()). The right list though does not re-render, even though it gets the same props.
Why does the left list rerender, but the right list not? The reducer is immutable, the selector is too and even the length of the list changes from one to zero which should eliminate the possibility of a shallow equal.
And now for the code:
waitercallsReducer:
import { createSelector } from "reselect";
const initialState = {};
const waitercallsReducer = (state = initialState, action) => {
if (action.payload && action.payload.entities && action.payload.entities.waitercalls) {
return {
...state,
...action.payload.entities.waitercalls
};
} else {
return state;
}
};
export default waitercallsReducer;
export const getAllWaitercallsNormalizedSelector = state => state.waitercalls;
export const getAllWaitercallsSelector = createSelector(
getAllWaitercallsNormalizedSelector,
waitercalls => Object.values(waitercalls)
);
export const getAllActiveWaitercallsSelector = createSelector(
getAllWaitercallsSelector,
waitercalls => waitercalls.filter(waitercall => !waitercall.done)
);
Action creators:
import { setValues } from "../core/core";
// feature name
export const WAITERCALLS = "[Waitercalls]";
// action creators
export const setValues = (values, type) => ({
type: `SET ${type}`,
payload: values,
meta: { feature: type }
});
export const setWaitercalls = waitercalls => setValues(waitercalls, WAITERCALLS);
HomeScreen:
import React, { Component } from "react";
import { View, TouchableOpacity } from "react-native";
import { SafeAreaView } from "react-navigation";
import { connect } from "react-redux";
import { Icon } from "react-native-elements";
import PropTypes from "prop-types";
// ... I've omitted all the imports so that it's shorter
export class HomeScreen extends Component {
// ... I've omitted navigationOptions and propTypes
render() {
const {
checkins,
customChoiceItems,
menuItemPrices,
menuItems,
orders,
pickedRestaurant,
tables,
waitercalls
} = this.props;
console.log("Rendering HomeScreen");
return (
<SafeAreaView style={styles.container}>
<View style={styles.activeOrders}>
<OrdersList
checkins={checkins}
customChoiceItems={customChoiceItems}
menuItemPrices={menuItemPrices}
menuItems={menuItems}
orders={orders}
restaurantSlug={pickedRestaurant.slug}
tables={tables}
waitercalls={waitercalls}
/>
</View>
<View style={styles.tableOvewView}>
<TableOverview
checkins={checkins}
orders={orders}
tables={tables}
waitercalls={waitercalls}
/>
</View>
</SafeAreaView>
);
}
}
const mapStateToProps = state => ({
checkins: getAllCheckinsSelector(state),
customChoiceItems: getAllCustomChoiceItemsNormalizedSelector(state),
menuItemPrices: getAllMenuItemPricesNormalizedSelector(state),
menuItems: getAllMenuItemsNormalizedSelector(state),
orders: getActiveOrdersSelector(state),
pickedRestaurant: getPickedRestaurantSelector(state),
tables: getAllTablesSelector(state),
waitercalls: getAllActiveWaitercallsSelector(state)
});
export default connect(mapStateToProps)(HomeScreen);
OrdersList (as you can see OrdersList also allows presses for orders, which displays the same erroneous behaviour of not having the TableOverView rerender), which is the left list with the clickable <ListItem />s.
import React, { PureComponent } from "react";
import { FlatList, Image, Text } from "react-native";
import { ListItem } from "react-native-elements";
import { connect } from "react-redux";
import PropTypes from "prop-types";
// ... omitted imports
export class OrdersList extends PureComponent {
// omitted propTypes
keyExtractor = item => item.uuid;
registerItem = item => {
// Remember the order status, in case the request fails.
const { restaurantSlug, setOrders } = this.props;
const itemStatus = item.orderStatus;
const data = {
restaurant_slug: restaurantSlug,
order_status: "registered",
order_uuid: item.uuid
};
setOrders({
entities: { orders: { [item.uuid]: { ...item, orderStatus: data.order_status } } }
});
postOrderStatusCreate(data)
.then(() => {})
.catch(err => {
// If the request fails, revert the order status change and display an alert!
alert(err);
setOrders({ entities: { orders: { [item.uuid]: { ...item, orderStatus: itemStatus } } } });
});
};
answerWaitercall = item => {
const { restaurantSlug, setWaitercalls } = this.props;
const data = {
done: true,
restaurant_slug: restaurantSlug
};
setWaitercalls({ entities: { waitercalls: { [item.uuid]: { ...item, done: true } } } });
putUpdateWaitercall(item.uuid, data)
.then(() => {})
.catch(err => {
alert(err);
setWaitercalls({ entities: { waitercalls: { [item.uuid]: { ...item, done: false } } } });
});
};
renderItem = ({ item }) => {
const { checkins, customChoiceItems, menuItemPrices, menuItems, tables } = this.props;
return item.menuItem ? (
<ListItem
title={`${item.amount}x ${menuItems[item.menuItem].name}`}
leftElement={
<Text style={styles.amount}>
{tables.find(table => table.checkins.includes(item.checkin)).tableNumber}
</Text>
}
rightTitle={`${
menuItemPrices[item.menuItemPrice].label
? menuItemPrices[item.menuItemPrice].label
: menuItemPrices[item.menuItemPrice].size
? menuItemPrices[item.menuItemPrice].size.size +
menuItemPrices[item.menuItemPrice].size.unit
: ""
}`}
subtitle={`${
item.customChoiceItems.length > 0
? item.customChoiceItems.reduce((acc, customChoiceItem, index, arr) => {
acc += customChoiceItems[customChoiceItem].name;
acc += index < arr.length - 1 || item.wish ? "\n" : "";
return acc;
}, "")
: null
}${item.wish ? "\n" + item.wish : ""}`}
onPress={() => this.registerItem(item)}
containerStyle={styles.alignTop}
bottomDivider={true}
/>
) : (
<ListItem
title={
item.waitercallType === "bill"
? SCREEN_TEXT_HOME_BILL_CALLED
: SCREEN_TEXT_HOME_SERVICE_ASKED
}
leftElement={
<Text style={styles.amount}>
{
tables.find(table =>
table.checkins.includes(
checkins.find(checkin => checkin.consumer === item.consumer).uuid
)
).tableNumber
}
</Text>
}
rightIcon={{
type: "ionicon",
name: item.waitercallType === "bill" ? "logo-euro" : "ios-help-circle-outline"
}}
onPress={() => this.answerWaitercall(item)}
bottomDivider={true}
/>
);
};
render() {
const { orders, waitercalls } = this.props;
return (
<FlatList
keyExtractor={this.keyExtractor}
data={[...orders, ...waitercalls]}
renderItem={this.renderItem}
// ... omitted ListHeader and ListEmpty properties
/>
);
}
}
export default connect(
null,
{ setOrders, setWaitercalls }
)(OrdersList);
TableOverview, which is the right <FlatList />:
import React, { Component } from "react";
import { FlatList } from "react-native";
import PropTypes from "prop-types";
// ... omitted imports
export class TableOverview extends Component {
// ... omitted propTypes
keyExtractor = item => item.uuid;
renderItem = ({ item }) => {
const { checkins, orders, waitercalls } = this.props;
if (item.invisible) return <Table table={item} />;
console.log("Rendering TableOverview");
return (
<Table
table={item}
hasActiveOrders={orders.some(order => item.userOrders.includes(order.uuid))}
billWanted={item.checkins.some(checkin =>
waitercalls.some(
waitercall =>
waitercall.waitercallType === "bill" &&
waitercall.consumer ===
checkins.find(checkinObj => checkinObj.uuid === checkin).consumer
)
)}
serviceWanted={item.checkins.some(checkin =>
waitercalls.some(
waitercall =>
waitercall.waitercallType === "waiter" &&
waitercall.consumer ===
checkins.find(checkinObj => checkinObj.uuid === checkin).consumer
)
)}
/>
);
};
formatData = (data, numColumns) => {
const numberOfFullRows = Math.floor(data.length / numColumns);
let numberOfElementsLastRow = data.length - numberOfFullRows * numColumns;
while (numberOfElementsLastRow !== numColumns && numberOfElementsLastRow !== 0) {
data.push({ uuid: `blank-${numberOfElementsLastRow}`, invisible: true });
numberOfElementsLastRow++;
}
return data;
};
render() {
const { tables } = this.props;
return (
<FlatList
style={styles.container}
keyExtractor={this.keyExtractor}
data={this.formatData(tables, NUM_COLUMNS)}
renderItem={this.renderItem}
numColumns={NUM_COLUMNS}
/>
);
}
}
export default TableOverview;
I found the solution!
The List was not rerendering, because the <FlatList /> only looked at the tables and not the waitercalls.
I had to add the following property to the <FlatList />:
extraData={[...checkins, ...orders, ...waitercalls]}

React Native - Adding items to FlatList using Redux

I'm trying to implement a simple ToDo list exercise app with Redux.
I have a TextInput, a Button and a FlatList, the items are stored as an array in the store and handled by a reducer.
When the button is pressed an item with the text from the input should be
added to the list.
Currently when I press the button nothing happens, the list does not seem to render and new elements are not added.
I suspect something could be wrong in the onPress handling but I'm not sure, I could have made mistakes elsewhere, I'm pretty new to React Native
Any help for figuring this out is welcome.
This is my code so far (without the imports):
action
export const addItem = item =>({type: ADD_ITEM, payload: item});
reducer
const initialState = {
items: [],
};
const itemReducer = (state = initialState, action) => {
switch(action.type) {
case ADD_ITEM:
return { ...state, items: [...state.items, action.payload] };
default:
return state;
}
};
export default itemReducer;
store
const store = createStore(itemReducer);
export default store;
input form
const mapDispatchToProps = dispatch => {
return {
addItem: item => dispatch(addItem(item))
};
};
class ItemInput extends Component {
constructor(props) {
super(props);
this.state = { itemText: 'Add an item' };
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit() {
//event.preventDefault();
const { itemText } = this.state;
this.props.addItem( { itemText } );
this.setState({ itemText: "" });
}
render() {
return (
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(itemText) => this.setState({itemText})}
value={this.state.itemText}
/>
<Button
onPress={this.handleSubmit}
title="Submit"
color="#841584"
/>
</View>
);
}
}
export default ItemInput = connect(null, mapDispatchToProps)(ItemInput);
list
const mapStateToProps = state => {
return { items: state.items };
};
class ItemList extends Component {
constructor(props) {
super(props);
this.state = {
};
this.renderItem = this.renderItem.bind(this);
this.keyExtractor = this.keyExtractor.bind(this);
}
render() {
return (
<View style={{flex:1, backgroundColor: '#F5F5F5', paddingTop:20}}>
<FlatList
ref='listRef'
data={this.props.items}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}/>
</View>
);
}
keyExtractor = (item, index) => index.toString();
renderItem({item, index}) {
return (
<View style={{backgroundColor: 'white'}}>
<Text>{item.title}</Text>
</View>
)
}
}
export default List = connect(mapStateToProps)(ItemList);
todo list component
class ToDoList extends Component {
render() {
return (
<View>
<ItemInput/>
<List/>
</View>
);
}
}
export default ToDoList;
App (root)
export default class App extends Component {
render() {
return (
<Provider store={store}>
<ToDoList/>
</Provider>
);
}
}

Resources