I've got this action creator :
export function getLevelsMap() {
const request = axios.get(`/api/levels`);
return {
type: GET_LEVELS_MAP,
payload: request
}
}
and this reducer
import { GET_LEVELS_MAP } from '../actions';
export default function (state = null, action) {
switch (action.type) {
case GET_LEVELS_MAP:
return action.payload.levels;
default:
return state;
}
}
The AJAX request is supposed to return me this :
{
"levels": [
{
"_id": "5951b7f0600af549fb1d269a",
"name": "College",
"__v": 0,
"subjects": [
{
"_id": "594891db1dbdf635ca3019ab",
"name": "Maths",
"__v": 0
},
{
"_id": "5948920d1dbdf635ca3019ac",
"name": "Biology",
"__v": 0
}
...
And the request does work (I've tested it with PostMan)
Now, I am connecting my component with the reducer and the action :
function mapStateToProps(state) {
return {
levels: state.levels
}
};
export default connect(mapStateToProps, { getLevelsMap })(ChooseSubject);
I am fetching the data (calling the action) in the componentDidMount method :
componentDidMount() {
if (!this.props.levels) {
this.props.getLevelsMap();
}
}
and trying to use the reducer :
getSubjects(level) {
let levels = this.props.levels;
if (levels) {
for (var item of levels) {
if (item.name === level) {
return item;
}
}
}
return null;
}
Here is where i state i am using promise middleware
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<Switch>
<Route path="/" component={HomePage} />
</Switch>
</BrowserRouter>
</Provider>
, document.querySelector('.root'));
BUT, this.props.levels is undefined ... PS : Everything works if I hardcode (copy paste the result i got from postMan in the subjects_reducer) the answer from the AJAX request.
Thank you very much for your very appreciated help :)