Reputation: 147
I have this configuration when using react-redux connect().
const mapStateToProps = state => ({
...state
});
const mapDispatchToProps = dispatch => ({
addMessage: msg => dispatch(addMessage(msg))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(RoomChat);
When using this.props.chats
I am getting "TypeError: Cannot read property 'map' of undefined"
.
This is the state, an array of objects that have the fields of 'username' and 'content':
chats = [{ content: '', username: '' }]
It is define in the RoomChat.js like this:
this.state = {
chats: []
};
This is the store.js where the redux store is defined:
import { createStore } from 'redux';
import MessageReducer from './reducers/MessageReducer';
function configureStore(chats = [{ content: '', username: '' }]) {
return createStore(MessageReducer, chats);
}
export default configureStore;
Reducer:
export default (state, action) => {
switch (action.type) {
case 'addMessage':
return {
content: action.text,
username: 'R'
};
default:
return state;
}
};
action:
export function addMessage(text) {
return { type: 'addMessage', text };
}
What went wrong here ?, I have tried multiple configurations without success so far
Upvotes: 0
Views: 74
Reputation: 1082
In your mapStateToProps
function, you need to do this...
const mapStateToProps = state => ({
chats: state
});
This is because you're creating your store with the chats
array when you do createStore(MessageReducer, chats)
.
So the state
is automatically chats
UPDATE In addition to @smoak's comment, you need to update your reducer like this
export default (state, action) => {
switch (action.type) {
case 'addMessage':
return [
...state,
{
content: action.text,
username: 'R'
}
];
default:
return state;
}
};
Upvotes: 1
Reputation: 26
Mabye try this
const mapStateToProps = state => {return {chats: state.chats}};
or this
const mapStateToProps = state => { return {...state}};
You need to return object in mapStateToProps and mapDistpachToProps.
Upvotes: 0