I was trying to use Redux in my React Native project to create a counter app. But then I encounter this error. It says sth like undefined is not an object (evaluating 'state.counter')
Please have a look at my code.
Counter.js
class Counter extends Component {
state = {counter: 0};
render() {
return (
<View style={styles.container}>
<View style={styles.counterPart}>
<TouchableOpacity onPress={() => this.props.increaseCounter()}>
<Text style={styles.text}>Increase</Text>
</TouchableOpacity>
<Text style={styles.text}>{this.props.counter}</Text>
<TouchableOpacity onPress={() => this.props.decreaseCounter()}>
<Text style={styles.text}>Decrease</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
function mapStateToProps(state) {
return {
counter: state.counter,
};
}
function mapDispatchToProps(dispatch) {
return {
increaseCounter: () => dispatch({type: 'INCREASE_COUNTER'}),
decreaseCounter: () => dispatch({type: 'DECREASE_COUNTER'}),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
The error seems to result from mapStateToProps(state) function above.
App.js
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREASE_COUNTER':
console.log('Enter INCREASE_COUNTER reducer');
return {counter: state.counter + 1};
case 'DECREASE_COUNTER':
console.log('Enter DECREASE_COUNTER reducer');
return {counter: state.counter - 1};
}
return state;
};
const store = createStore(reducer);
const initialState = {
counter: 0,
};
class App extends Component {
render() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
}
I would appreciate if you can provide a solution or a suggestion to this issue. Thank you.
I think the problem is that you can't access to initialState in reducer, try to move declaration on the top of reducer like so.
const initialState = {
counter: 0,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
...
}
}
I think that your problem will be solved by adding default situation in switch.
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREASE_COUNTER':
console.log('Enter INCREASE_COUNTER reducer');
return {counter: state.counter + 1};
case 'DECREASE_COUNTER':
console.log('Enter DECREASE_COUNTER reducer');
return {counter: state.counter - 1};
default: // <--- HERE
return state; // <--- HERE
}
};
Related
need some serious help here. I am currently using a class component to add my items to cart but it looks like i keep getting undefined, can someone point me in the right direction please?
Homepage :
const mapStateToProps = state => ({
cartItems: state.cart.cartItems
});
const mapDispatchToProps = dispatch => {
return {
addToCartHandler: item => {
dispatch(addToCart(item))
}
}
}
renderRow =({item}) =>{
console.log(this.state.cartItems)
return(
<TouchableHighlight >
<View style ={styles.card}>
<Image source={{uri:item.image}} style={styles.image} />
<Icon name="add" size ={20} style= {styles.addToCartBtn} onPress ={() => this.props.addToCartHandler(item)} />
</TouchableHighlight>
)
}
reducers
import { ADD_TO_CART } from '../constants'
const initialState = {
cartItems: [],
totalPrice :0
}
//add item
export const cart = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
console.log("reducer",action)
var {item} =action.payload;
var newState =Object.assign({},{...state});
for (var i = 0; i < state.cartItems.length; i++) {
newState.cartItems = newState.cartItems.concat(item);
console.log(newState)
return newState
}
default:
return state
}
}
action
import {ADD_TO_CART} from '../constants'
import {REMOVE_FROM_CART} from '../constants'
export const addToCart =(item) =>{
// console.log(item)
return{
type: ADD_TO_CART,
payload : item,
};
}
Dont think anything is wrong with my action or rootreducers. I am not sure why i keep getting undefined whenever i add to cart when i can console.log the item
You are not creating the new state correctly, I think the following will work:
case ADD_TO_CART:
console.log('reducer', action);
var item = action.payload;
return {
...state,
cartItems:state.cartItems.concat(item)
}
Here is some useful information on how to create a new state.
I'm creating react native app with redux state management. I want to know what is the best practice of having connect(mapStateToProps, mapDispatchToProps).
I have several component classes i.e. ParentA, ChildA, ChildB. Currently I'm getting state properties for each parent and child classes independently.
eg:
const ParentA = (props) => {
return (
<View>
<Text>{props.item.name}</Text>
<ChildA />
<ChildB />
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default connect(mapStateToProps)(ParentA)
const ChildA = (props) => {
return (
<View>
<Text>{props.item.name}</Text>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default connect(mapStateToProps)(ChildA)
const ChildB = (props) => {
return (
<View>
<Text>{props.item.age}</Text>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default connect(mapStateToProps)(ChildB)
But rather having connect for each child component I could get item state from ParentA and pass it to Child components.
eg:
const ParentA = (props) => {
return (
<View>
<Text>{props.item.name}</Text>
<ChildA item={item}/>
<ChildB item={item}/>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default connect(mapStateToProps)(ParentA)
const ChildA = (props) => {
return (
<View>
<Text>{props.item.name}</Text>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default ChildA
const ChildB = (props) => {
return (
<View>
<Text>{props.item.age}</Text>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default ChildB
My questions are,
What would be the best approach while considering the app performance ?
Can I use same approach for mapDispatchToProps as well ?
Yes, you can Use useSelector, useDispatch but the thing is you should use hooks. It can fix considering the app performance with this approach.
I think rather than using 'const', try another datatypes such as 'var' or 'let' as 'const' value once fixed cannot be changed.
I am implementing redux in react-native project. I have some asyn action and some pure actions. I am unable to get state value in my component. How do I get it.?
class Gender extends Component {
constructor(props) {
super(props);
}
nextScr = (gend) => {
alert(`gen: ${gend} \n this.props.gen: ${this.props.gen}`)
//***** here I am getting undefined ****
if(gend!= null) {
this.props.navigation.navigate('Info');
}
}
render() {
const { gen } = this.props;
return (
<View style={style.container}>
<View style={style.bcont}>
{/* this.storeData("Male") this.storeData("Female") */}
<Btn name="gender-male" txt="Male" click={() => this.props.saveMale('male')}
bstyl={(gen == 'Male') ? [style.btn, style.btnsel] : style.btn} />
<Text style={style.hi}>OR</Text>
<Btn name="gender-female" txt="Female" click={() => this.props.saveFemale('female')}
bstyl={(gen == 'Female') ? [style.btn, style.btnsel] : style.btn} />
</View>
<Text>Gender Value is: {this.props.gen}</Text>
// **** here not getting gen value ****
<Next name="chevron-right" nextClk={ () => this.nextScr(gen)} />
</View>
);
}
}
const mapStateToProps = state => {
const { gen } = state
return {
gen: gen,
};
};
const mapDispatchToProps = dispatch => {
return {
saveMale: (gen) => {
dispatch(saveMale(gen));
},
saveFemale: (gen) => {
dispatch(saveFemale(gen));
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Gender);
These are my actions:
export const saveMale = (gen) => ({
type: MALE_SAVE,
payload: gen
});
export const saveFemale = (gen) => ({
type: FEMALE_SAVE,
payload: gen
});
Following is my reducer:
const initialState = {
gen: null
}
export function genSave(state=initialState, action) {
switch(action.type) {
case MALE_SAVE:
alert(`state in MALE_SAVE: ${action.payload}`);
return { ...state, gen: action.payload };
case FEMALE_SAVE:
alert(`state in FEMALE_SAVE: ${action.payload}`);
return { ...state, gen: action.payload };
default:
alert(`state in default gender save: ${JSON.stringify(state)}`);
return state;
};
}
I am getting action.payload alert values but in the component I am not getting values. How do I solve this problem ?? Thanks in advance.
Can you try like this?
...
nextScr(gend) {
alert(`gen: ${gend} \n this.props.gen: ${this.props.gen}`)
if(gend!= null) {
this.props.navigation.navigate('Info');
}
}
render() {
const { gen } = this.props;
return (
<View style={style.container}>
<View style={style.bcont}>
{/* this.storeData("Male") this.storeData("Female") */}
<Btn name="gender-male" txt="Male" click={() => this.props.saveMale('male')}
bstyl={(gen == 'Male') ? [style.btn, style.btnsel] : style.btn} />
<Text style={style.hi}>OR</Text>
<Btn name="gender-female" txt="Female" click={() => this.props.saveFemale('female')}
bstyl={(gen == 'Female') ? [style.btn, style.btnsel] : style.btn} />
</View>
<Text>Gender Value is: {this.props.gen}</Text>
<Next name="chevron-right" nextClk={ () => this.nextScr(this.props.gen)} />
</View>
);
}
...
I believe your mapStateToProps could be the problem depending on how you initialize your store. Right now it assumes gen is a property on the base store but it is likely you have a combineRecucers call when you create the store that adds another object layer.
a component dispatches an action which modifies the Redux store and the other component should get the changed state to props and rerender.
The thing is, the component gets the props, and they are correct and modified, but the component is never rerendered.
Could someone help, been stuck too much..
Component who uses store:
on mount it does a http request,
and should rerender when the state is changed.
class CalendarView extends Component {
componentDidMount() {
axios.get('http://localhost:3000/api/bookings/get')
.then(foundBookings => {
this.props.getBookings(foundBookings);
})
.catch(e => console.log(e))
}
render() {
return (
<Agenda
items={this.props.items}
selected={this.props.today}
maxDate={this.props.lastDay}
onDayPress={this.props.setDay}
renderItem={this.renderItem}
renderEmptyDate={this.renderEmptyDate}
rowHasChanged={this.rowHasChanged}
/>
);
}
renderItem = (item) => {
return (
<View style={[styles.item, { height: item.height }]}>
<Text>Name: {item.name} {item.surname}</Text>
<Text>Time: {item.time}</Text>
</View>
);
}
renderEmptyDate = () => {
return (
<View style={styles.emptyDate}><Text>This is empty date!</Text></View>
);
}
rowHasChanged = (r1, r2) => {
console.log('hit')
return true;
}
}
const mapStateToProps = (state, ownProps) => {
return {
today: state.app.today,
lastDay: state.app.lastDay,
items: state.app.items
}
}
const mapDispatchToProps = (dispatch) => {
return {
setDay: date => dispatch(appActions.setSelectionDate(date.dateString)),
getBookings: data => dispatch(appActions.getBookings(data)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CalendarView);
Action Dispatching:
dispatches an action which modifies the state
onSubmit = (name, surname, selectionDate, selectionTime) => {
axios.post('http://localhost:3000/api/bookings/create', {
bookerName: name,
bookerSurname: surname,
bookerTime: selectionTime,
date: selectionDate
}).then(savedBookings => {
this.props.createBooking(savedBookings);
this.props.navigator.pop({
animationType: 'slide-down',
});
}).catch(e => console.log(e))
}
const mapStateToProps = state => {
//...
}
const mapDispatchToProps = (dispatch) => {
return {
createBooking: data => dispatch(appActions.createBooking(data))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(NewBookingScreen);
Reducer:
case types.CREATE_BOOKING: {
const { date , bookings } = action.savedBookings.data;
let dateArr = state.items;
// formatting a booking how needed
Object.keys(dateArr).forEach(key => {
if (key == date) {
dateArr[key] = [];
bookings.map(oneBooking => {
dateArr[key].push({
name: oneBooking.bookerName,
surname: oneBooking.bookerSurname,
time: oneBooking.bookerTime,
height: Math.max(50, Math.floor(Math.random() * 150))
});
})
}
});
return {
...state,
items: dateArr
};
}
full repo if needed: https://github.com/adtm/tom-airbnb/tree/feature/redux
Thank You in advance!
Your reducer is mutating the state, so connect thinks nothing has changed. In addition, your call to map() is wrong, because you're not using the result value.
Don't call push() on an array unless it's a copy. Also, please don't use any randomness in a reducer.
For more info, see Redux FAQ: React Redux ,Immutable Update Patterns, and Roll the Dice: Random Numbers in Redux .
I have a react native app using redux and immutable js. When i dispatch an action from my main screen, it goes through my actions, to my reducer and then back to my container, however, the view doesn't update and componentWillReceieveProps is never called. Furthermore, the main screen is a list whose items are sub components Item. Here's the relevant code for the issue, if you want to see more let me know.
Render the row with the data:
renderRow(rowData) {
return (
<Item item={ rowData } likePostEvent={this.props.likePostEvent} user={ this.props.user } removable={ this.props.connected } />
)
}
The part of Item.js which dispatches an action, and shows the result:
<View style={{flex: 1, justifyContent:'center', alignItems: 'center'}}>
<TouchableOpacity onPress={ this.changeStatus.bind(this, "up") }>
<Image source={require('../img/up-arrow.png')} style={s.upDownArrow} />
</TouchableOpacity>
<Text style={[s.cardText,{fontSize:16,padding:2}]}>
{ this.props.item.starCount }
</Text>
<TouchableOpacity onPress={ this.changeStatus.bind(this, "down") }>
<Image source={require('../img/up-arrow.png')} style={[s.upDownArrow,{transform: [{rotate: '180deg'}]}]} />
</TouchableOpacity>
</View>
The action dispatched goes to firebase, which has an onChange handler that dispatches another action.
The reducer:
const initialState = Map({
onlineList: [],
offlineList: [],
filteredItems: [],
connectionChecked: false,
user: ''
})
...
...
case ITEM_CHANGED:
list = state.get('onlineList')
if(state.get('onlineList').filter((e) => e.id == action.item.id).length > 0){
let index = state.get('onlineList').findIndex(item => item.id === action.item.id);
list[index] = action.item
list = list.sort((a, b) => b.time_posted - a.time_posted)
}
return state.set('onlineList', list)
.set('offlineList', list)
The container:
function mapStateToProps(state) {
return {
onlineItems: state.items.get('onlineList'),
offlineItems: state.items.get('offlineList'),
filteredItems: state.items.get('filteredItems'),
connectionChecked: state.items.get('connectionChecked'),
connected: state.items.get('connected'),
user: state.login.user
}
}
Where I connect the onChange:
export function getInitialState(closure_list) {
itemsRef.on('child_removed', (snapshot) => {
closure_list.removeItem(snapshot.val().id)
})
itemsRef.on('child_added', (snapshot) => {
closure_list.addItem(snapshot.val())
})
itemsRef.on('child_changed', (snapshot) => {
closure_list.itemChanged(snapshot.val())
})
connectedRef.on('value', snap => {
if (snap.val() === true) {
closure_list.goOnline()
} else {
closure_list.goOffline()
}
})
return {
type: GET_INITIAL_STATE,
connected: true
}
}
Calling get initial state:
this.props.getInitialState({
addItem: this.props.addItem,
removeItem: this.props.removeItem,
goOnline: this.props.goOnline,
goOffline: this.props.goOffline,
itemChanged: this.props.itemChanged
})
Any suggestions are welcome, thanks so much!
The source of your issue could be with the call to Firebase. If it is an asynchronous call, it's return callback might not be returning something that can be consumed by your action.
Do you know if it is returning a Promise? If that is the case, middleware exists that handle such calls and stops the calling of an action until a correct response is received. One such middleware is Redux-Promise.
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore,combineReducers } from 'redux' //Redux.createStore
import { Provider,connect } from 'react-redux';
//Функція яка змінює store
const hello = (state= {message:'none'}, action) => {
switch (action.type) {
case 'HELLO':
return Object.assign({}, state, {message:"hello world"});
break
case 'buy':
return Object.assign({}, state, {message:"buy"});
break;
case 'DELETE':
return Object.assign({}, state, {message:"none"});
break;
default :
return state;
}
};
const price = (state= {value:0}, action) => {
switch (action.type) {
case 'HELLO':
return Object.assign({}, state, {value: state.value + 1 });
break;
default :
return Object.assign({}, state, {value:0});
}
};
const myApp = combineReducers({
hello,price
});
//створюємо store
let store = createStore(myApp);
let unsubscribe = store.subscribe(() => console.log(store.getState()))
//VIEW
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>value: {this.props.price}</p>
<a href="#" onClick={this.props.onClick}>click</a><b>{this.props.message}</b>
</div>
)
}
}
//mapStateToProps() для чтения состояния и mapDispatchToProps() для передачи события
const mapStateToProps = (state, ownProps) => {
return {
message: state.hello.message,
price: state.price.value
}
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClick: () => {
var items= ['HELLO','buy','DELETE','error']
var item = items[Math.floor(Math.random()*items.length)];
dispatch({ type: item })
}
}
}
const ConnectedApp = connect(
mapStateToProps,
mapDispatchToProps
)(App);
ReactDOM.render(
<Provider store={store}>
<ConnectedApp />
</Provider>,
document.getElementById('app')
);