Reputation: 2027
I'm having problem with an api call in my React Redux project. Here's the code snippet from the project.
poiAction.js
export function poiSuccess(pois) {
// The log detail is below
console.log("POI: ", pois);
return {
pois,
type: POI_FETCH_SUCCESS
};
}
export function poiFetch(pois) {
return {
pois,
type: POI_FETCH_ATTEMPT
};
}
export function fetchPoi(token) {
return dispatch =>
axios({
method: 'get',
url: 'http://localhost:9090/poi',
headers: {
'x-access-token': token
},
})
.then((pois) =>{
// let poi = pois.data[0];
// console.log("POIS: ", pois.data[0]);
dispatch(poiSuccess(pois));
})
.catch((error) => {
throw(error);
})
}
console log output:
poiReducer.js
export default function poi(state = [], action){
switch(action.type){
case POI_FETCH_ATTEMPT:
return state;
case POI_FETCH_FAILED:
return state;
case POI_FETCH_SUCCESS:
// The console log output is same as poiAction
console.log("Reducer: ", action.pois);
return [action.pois, ...state];
break;
default:
return state;
}
}
The console log output is same as poiAction
Root Reducer
const rootReducer = combineReducers({
LoginReducer,
PoiReducer
});
The component to display the list from the api call:
Dashboard.js
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
poi: '',
token: null
};
}
componentWillMount() {
let token = sessionStorage.getItem("token");
this.setState({token});
this.props.actions.fetchPoi(token);
}
render() {
console.log("POIS: ", this.props.pois);
return (
<div>
<h1>Dashboard</h1>
</div>
);
}
}
Dashboard.propTypes = {
pois: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
console.log("State: ", state);
return {
pois: state.poiReducer
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(poiAction, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
Here this.props.pois
is undefined
and the value of state
from mapStateToProps
is:
What am I missing? How do I access the list that's returning from the api call ?
Thanks
Upvotes: 0
Views: 245
Reputation: 28397
When you combine your reducers, you do this
const rootReducer = combineReducers({
LoginReducer,
PoiReducer
});
which means
const rootReducer = combineReducers({
LoginReducer : LoginReducer,
PoiReducer : LoginReducer
});
And that's not what you want.
it should be
const rootReducer = combineReducers({
loginReducer : LoginReducer,
poiReducer : LoginReducer
});
Also, for some reason, you got a rootReducer inside your root reducer, which is a little weird.
So the way to access to poiReducer would be
function mapStateToProps(state) {
console.log("State: ", state);
return {
pois: state.rootReducer.poiReducer
};
}
Upvotes: 1