reducer isn't triggered (redux-promise with axios)

253 views Asked by At

I'm trying to make an api call in action with axios and pass the results of it to the reducer. Though action is triggered, reducer isn't. And I can't understand why.

Here's the component that should make api call before mounting

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

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


class PostShow extends Component {
 constructor(props) {
  super(props);

 }

 componentWillMount() {
  getPost(this.props.params.id);
 }
 

 render() {
  console.log(this.props.activePost);
  return (
   <div>
    <h1> hello from a post</h1>
   </div>
  )
 }
}


const mapStateToProps = (state) => {
 return {
  activePost: state.posts.activePost
 }
};

const mapDispatchToProps = (dispatch) => {
 return bindActionCreators({
  getPost
 }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(PostShow);

Here's my action

import axios from 'axios';

import { FETCH_POSTS, SEND_POST, FETCH_POST } from './types';

const ROOT_URL = 'http://reduxblog.herokuapp.com/api';
const API_KEY = '?key=qwerty';

export function fetchPosts() {
 const req = axios.get(`${ROOT_URL}/posts${API_KEY}`);

 return {
  type: FETCH_POSTS,
  payload: req
 }
}

export function sendPost(props) {
 const req = axios.post(`${ROOT_URL}/posts${API_KEY}`, props);

 return {
  type: SEND_POST,
  payload: req
 }

}

export function getPost(id) {
 console.log('action triggered');
 const req = axios.get(`${ROOT_URL}/posts/${id}${API_KEY}`);

 return {
  type: FETCH_POST,
  payload: req
 }
}

And here's my reducer

import { FETCH_POSTS, FETCH_POST } from '../actions/types';

const INITIAL_STATE = {
 allPosts: [],
 activePost: null
};

export default (state = INITIAL_STATE, action) => {
 switch (action.type) {
  case FETCH_POSTS:
   return {
    ...state,
    allPosts: action.payload.data
   };
  case FETCH_POST:
   console.log('reducer triggered');
   return {
   ...state,
   activePost: action.payload.data
  };
  default:
   return state;
 }
}

As a result I see 'action triggered' coming from console.log in action, and null coming from console.log in component, and no console.log from the reducer, so it's not triggered and I have no data to render in my component. Though I make a request and get a response from server with the data, it doesn't go to the reducer. (moreover case FETCH_POSTS works fine and I can render a list of posts, but not a particular one).

"axios": "^0.17.0" "redux-promise": "^0.5.3"

1

There are 1 answers

0
lavish On BEST ANSWER

You need to use this.props.getPost in componentDidMount instead of getPost.

Connect sends bound action creator to component as a prop