mapStateToProps() in Redux app nesting state within state?
So your mapStateToProps
value of data
is returning an object. You probably want this instead:
function mapStateToProps(state) {
console.log(state);
// this console.log shows the state with the data property.
return {
...state.app
};
}
This will give you access to the fields in your data
reducer. Also, it's not clear from the example exactly how you will use the data, or what fields are included in it. Also, to start with, your reducer is not initialized to null or empty values for the fields it will use, which can definitely cause errors. Probably better to start with an initialState
object:
const initialState = {
error: '',
loading: false,
data: []
};
const app = (state=initialState, action) => {
/* .... */
I was having a similar issue with mapStateToProps
, where on the first render it would nest the initial state in an object with the key of state. When I updated the state using a dispatch method it would create another key-value pair. (The below entry in the console is when I console log state inside the mapStateToProps function).
Initial State which is nested:
I released that in my reducer function, I was returning state for my default case.
const initialState = {
stateprop1: false,
user_text: "empty",
};
const reducer1 = (state = initialState, action) => {
switch (action.type) {
case ACTION_TYPES.SUCCESS:
return {
...state,
stateprop1: true,
};
case ACTION_TYPES.FAILURE:
return {
...state,
stateprop1: false,
};
case ACTION_TYPES.USER_INPUT:
return {
...state,
user_text: action.payload,
};
default:
return {
state,
};
}
};
If, instead, I spread the state in the default case, the nesting behaviour wasn't observed.
default:
return {
...state,
};
So now if I console log state in the mapStateToProps
function I get
State that isn't nested :
I hope this helps.
After much reviewing, debugging and asking other devs, in a nutshell this is the problem I was facing: The reducer and how it was being imported into a main "manifest" file to manage all other reducers.
Basically, since I was only using one reducer in this project, there was no need for a manifest reducer file. See below:
import { combineReducers } from 'redux';
import Reducer from './reducer';
const rootReducer = combineReducers({
state: Reducer
});
export default rootReducer;
I don't know exactly why this was nesting state. Perhaps because, theoretically, we would be dealing with multiple reducers with different purposes (like a data reducer and a user reducer) and would need to nest those into our state tree to manage.
state = {
// here is one nested reducer with its own properties
data: {
type: // somevalue,
filtered: true
},
// here is another
user: {
name: // somename,
password: // somepassword
}
};
In short...be mindful of how your reducer is being imported into your createStore
function and if it's the only reducer being used or if there's multiple reducers being run through a manifest file of sorts.
Cheers.