-1

Here is my code:

The action creator

export function fetchHead() {

  const url = HEAD_URL;

  const request = axios.get(url);

  return {

    type: FETCH_HEAD,

    payload: request

  };
}

The Reducer

import { FETCH_HEAD } from '../actions';

import _ from 'lodash';

export default function(state = {}, action) {

  switch (action.type) {

    case FETCH_HEAD:

      return _.mapKeys(action.payload.data.articles, 'id');

    default:

      return state;
  }

}

Reducer keys, promise

import { combineReducers } from 'redux';


import HeadReducer from './head_reducer';

const rootReducer = combineReducers({


  heads: HeadReducer

});

export default rootReducer;

Component

import React, { Component } from 'react';

import { connect } from 'react-redux';

import { fetchHead } from '../actions';

class HeadNews extends Component {

  componentDidMount() {

    this.props.fetchHead();

    console.log(this.props.heads);
  }

  render() {

    return <div>Hello</div>;

  }

}

function mapStateToProps(state) {

  return { heads: state.heads };

}

export default connect(mapStateToProps, { fetchHead })(HeadNews);
petezurich
  • 9,280
  • 9
  • 43
  • 57
RaMsIs
  • 1
  • 2
  • you are missing the async nature of network calls, api call will be asynchronous and it will not return the data synchronously, so you need to include some middleware like `Redux-thunk`, check these answers: [Why do we need middleware for async flow in Redux?](https://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux) and [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Mayank Shukla Sep 14 '17 at 19:20
  • I think redux-promise will solve that ! – RaMsIs Sep 14 '17 at 20:31

2 Answers2

0

You are passing a deffered object to the reducer and not the data returned from the ajax request.
You should use .then:

    axios.get(url)
      .then(function (response) {
        return {
          type: FETCH_HEAD,
          payload: response
        }
      })
      .catch(function (error) {
        console.log(error);
      });

EDIT
I don't know if you are using redux-thunk middleware but in order to dispatch actions that returns a function instead of a plain object like an action should be, you need to use redux-thunk.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
  • i don't think it will solve the OP's problem, he need some middleware like `thunk`. – Mayank Shukla Sep 14 '17 at 19:23
  • thanks, yeah i edited the answer, though whether the OP is using _redux-thunk_ or not he must return a plain object as an action (that can be serialized) and not the promise it self. – Sagiv b.g Sep 14 '17 at 20:40
0

Just but console.log under rendering funcnction :

componentDidMount() {

this.props.fetchHead();

}

render() {

console.log(this.props.heads);

return <div>Hello</div>;

}

RaMsIs
  • 1
  • 2